diff --git a/.github/workflows/app.yml b/.github/workflows/app.yml index c0f19ccefdb..8baf2162bbc 100644 --- a/.github/workflows/app.yml +++ b/.github/workflows/app.yml @@ -31,6 +31,18 @@ env: TRANSFORMERS_OFFLINE: '1' jobs: + computer-use-linux: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + container: + image: swift:6.2.3-noble@sha256:6dd90eb2359663a2cde8f03e9951f488b23134b3b8fce20e9dcb6cada75dd803 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - name: Test the shared computer-use parser and key table on Linux + run: swift test --package-path app/native/computer-use/ComputerUseChecks + desktop: runs-on: macos-15 timeout-minutes: 20 diff --git a/CHANGELOG.md b/CHANGELOG.md index 2693e2d4248..c060c25601d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,56 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel ## Unreleased +- Server: `background: true` on `POST /v1/responses` answers at once with a queued response and generates the reply after the POST returns; `GET /v1/responses/{id}` polls it and `POST /v1/responses/{id}/cancel` or `DELETE` stops it, at most 64 are queued or running per server (16 per key, 256 MiB of copied requests) before a create answers 429, and `stream: true` with `background` is refused (#3220). + +- Qwen 3.5 on CUDA: a dropped kept prompt state's pinned host buffer goes to a spare list of at most two, and the next save or recall blank of the same size reuses it instead of pinning new memory; spares count inside the prompt-cache budget and are freed before any state is evicted (#2841). + +- Flash Next: when an assistant makes several tool calls and their results arrive out of call order, each result is now placed after its own call's ID before the prompt is rendered, since Flash Next's template gives the model anonymous result blocks in order; only a contiguous run with exactly one result per call is reordered, any other run keeps arrival order, and every other request and backend renders as before (#3775). Thanks to @srh3877. + +- HIP: at head size 256 on long spans (16,384 keys or more), the planned decode walk scores keys in its own kernels without per-element tests or a per-key branch, with byte-identical scores (Qwen3.6-35B-A3B, Qwen3.8-27B); Nemotron's d = 128 kernels are unchanged (#3508). Thanks to @AbrahamCete. + +- Lanes: Qwen 3.5's bounded top-k row draw moves into core's shared sampler (`core/lanes/sampling_row_topk.zig`), the same code and the same tokens (#3214, part of #2460). Thanks to @jschmied. + +- Server: a slow grammar compile no longer holds up other requests' grammars; a request waits at most 2,000 ms for its grammar and past that gets HTTP 400 naming the limit, each model runs at most 4 compiles at once, and grammars that compile within the limit are unchanged (#3231). + +- App: confirming an `ultrathink` effort change now applies it (#3502). Thanks to @AIFlowML. + +- App: bots keep their own reasoning effort instead of sharing the app-wide setting (#3500). Thanks to @AIFlowML. + +- App: the Parallel search tests no longer depend on the system's DNS (#3489). Thanks to @AIFlowML. + +- App: Git keeps working in the sandbox when macOS selects Xcode without a legacy `xcode_select_link` (#3479). Thanks to @AIFlowML. + +- App: an oversized scroll delta is refused as a bad request instead of stopping the computer-use helper (#3470). Thanks to @AIFlowML. + +- App: returning a parked ticket to Ready releases its previous assignee, so another Room seat can take it (#3469). Thanks to @AIFlowML. + +- App: the computer-use key table and request parser are tested on Linux with Swift Testing; the native checks stay on macOS (#3465). Thanks to @AIFlowML. + +- App: Kanban tickets have a Details action to read and edit their title, description, type, priority and effort, and archived tickets can be restored (#3464). Thanks to @AIFlowML. + +- App: Room health shows each Room's worktree path and its Git branch (#3463). Thanks to @AIFlowML. + +- App: MCP servers bundled inside macOS apps can load their own frameworks; the bundle stays read-only and other app bundles stay out of reach (#3423). Thanks to @AIFlowML. + +- `tensorfold device`: when the memory reserve leaves a known zero bytes for weights, a nonempty checkpoint is reported too large and the text report shows 0.0 GiB; unknown memory keeps the old fallback (#3773, fixes #3770). Thanks to @AIFlowML. + +- macOS: the native binary imports `_memcpy` from libSystem again, so the release link check passes; the saved device profile is decoded with checked decimal arithmetic and keeps its format (#3761, fixes #3760). Thanks to @AIFlowML. + +- Server: a reranker server also answers `/score`, TEI's `/rerank` with `texts` and Cohere's `/v2/rerank`, each translated onto the existing `/v1/rerank` path (#3203). + +- Shared decoding: fixed DFlash2 block work stays separate from verification rows; MTP heads keep their step costs and copied rows keep their measured cost feedback (#3755). + +- Nemotron 3.5 Transcribe on CUDA: the language model loads from the bf16 release as published, with exact bf16 caches and no conversion. The audio encoder runs on the GPU: log-mel, the ASR encoder, the streaming speaker encoder and its cache, fusion and projection. `tf-cuda-test audio-check` writes every encoder stage. Every other Nemotron checkpoint loads as before, and audio input in the server follows in #1632 (#1631). Thanks to @BobClawblaw, and to @cwschroeder for the CI report. + +- CUDA: Gemma 4, Dory and Spark2.5 can keep conversations on disk through the shared kept-image store (#3135, part of #840). Thanks to @jschmied. + +- CUDA: a dense Qwen 3.5 MLP's NVFP4 prompt gate, up and activation run in one launch for prompt rows past 16, with the same bytes (#3252). Thanks to @jschmied. + +- Images: with `stream: true`, `POST /v1/images/generations` streams each denoising step's progress (`image_generation.progress`) and, with `preview_interval`, partial previews while the picture generates, then the PNG (#3245). + +- DeepSeek-V4.1 on Metal: decode launches of 6 to 16 rows (draft verify windows, alone or with other streams' rows) run the dense FP8 projections on a simdgroup-matrix tile that splits K over simdgroups in the row kernel's own group tree, so every row's bits equal the row kernel's one row at a time; launches of 1 to 5 rows keep the row kernel. On the release weights two drafted streams decode 3.7 to 5.5% faster on an M5 Ultra and 3.6 to 5.4% faster on an M3 Ultra, other stream counts are level, and every token is unchanged; `time-dsv41-metal-synth` times the dispatch classes per row without a checkpoint (#2973, part of #2984). + - Tools: add the heat-exchanger agent evaluation and its bounded Python execution helper (#3086). - Packaging: a Grafana dashboard for the engine's Prometheus metrics (TTFT and TPOT quantiles, decode rate, running and waiting requests, KV use, draft acceptance, prompt cache, memory and admission), with a host test that rejects unwritten metrics (#3141). @@ -13,6 +63,7 @@ Each release's page on GitHub has its notes and measurements. See [the 1.0.0 rel - Tests: `zig build test-tokenizer-host` runs every tokenizer test, unfiltered, on the host without a GPU or shader compiler, and is part of the nightly Linux and macOS fast checks; before, CI reached only the tokenizer's two EOS policy tests (#3082). - Bench: add served agent-cache traces and token-qualified A/B comparisons (#3263). - CI: remove the redundant nightly Linux host shard while retaining the fast, compile, HIP and DeepSeek shards (#3276). +- Metal: Spark2.5 and Llama build their tensor-unit prompt attention from one shared source, Llama's at WINDOW 0 and RING 0; the compiled code is unchanged (#3269, part of #2251). Thanks to @jschmied. - Docs: the README is now a short quick start and docs list; setup, serve flags and model tables moved to the new run guide and supported models pages, and the Zig preview and 1.0.0 release notes moved into docs/ (#3170). Thanks to @jayleaton. diff --git a/app/electron/agent/bot-reasoning-store.test.ts b/app/electron/agent/bot-reasoning-store.test.ts new file mode 100644 index 00000000000..fdbb1d2b860 --- /dev/null +++ b/app/electron/agent/bot-reasoning-store.test.ts @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { captureBotConfig } from '../../shared/bot-policy' +import type { AgentPreset, Provider, Thread } from './types' + +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'tensorfold-bot-effort-store-')) +const previousHome = process.env.VONTRA_HOME +process.env.VONTRA_HOME = profile +try { + const { loadSettings, saveSettings, loadThreads, saveThreads } = await import('../store') + const provider: Provider = { id: 'fixture', name: 'Local fixture', kind: 'local', baseUrl: 'http://127.0.0.1:1/v1', apiKey: '', models: ['fixture'] } + const preset: AgentPreset = { id: 'bot_effort', name: 'Careful reviewer', role: 'Review supplied text', lane: 'review', providerId: provider.id, model: 'fixture', reasoningEffort: 'high', createdAt: 1, updatedAt: 1 } + await saveSettings({ ...await loadSettings(), providers: [provider], agentPresets: [preset] }) + const restarted = await loadSettings() + assert.equal(restarted.agentPresets[0].reasoningEffort, 'high', 'protected settings retain per-bot effort across restart') + const bot = captureBotConfig(restarted.agentPresets[0], restarted.providers) + const thread: Thread = { id: 'effort-chat', title: 'Review', kind: 'chat', cwd: '', providerId: provider.id, providerAccountId: null, model: 'fixture', bot, status: 'idle', createdAt: 1, updatedAt: 1, timeline: [], apiMessages: [] } + await saveThreads([thread]) + await saveSettings({ ...restarted, agentPresets: [{ ...preset, reasoningEffort: 'low' }] }) + assert.equal((await loadSettings()).agentPresets[0].reasoningEffort, 'low') + assert.equal((await loadThreads())[0].bot?.reasoningEffort, 'high', 'persisted conversations keep their captured effort after a bot edit') + console.log('Protected bot effort settings and chat restart checks passed.') +} finally { + if (previousHome === undefined) delete process.env.VONTRA_HOME + else process.env.VONTRA_HOME = previousHome + await fs.rm(profile, { recursive: true, force: true }) +} diff --git a/app/electron/agent/mac-developer-directory.test.ts b/app/electron/agent/mac-developer-directory.test.ts new file mode 100644 index 00000000000..e76aa4adda3 --- /dev/null +++ b/app/electron/agent/mac-developer-directory.test.ts @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict' +import { resolveDeveloperReadRoot } from './mac-developer-directory' + +const link = '/var/db/xcode_select_link' +const clt = '/Library/Developer/CommandLineTools' +const selected = '/Applications/Selected Xcode.app/Contents/Developer' +let queries = 0 +const io = (paths: Record, choice: string | null = selected) => ({ + realpath(value: string) { + if (!(value in paths)) throw new Error('Missing fixture path') + return paths[value] + }, + selectedPath() { queries++; return choice }, +}) + +assert.equal(resolveDeveloperReadRoot(io({ [selected]: selected, [clt]: clt })), '/Applications/Selected Xcode.app') +assert.equal(queries, 1, 'missing legacy link asks xcode-select before choosing installed Command Line Tools') +queries = 0 +assert.equal(resolveDeveloperReadRoot(io({ [link]: selected })), '/Applications/Selected Xcode.app') +assert.equal(queries, 0, 'an existing selection link keeps the direct lookup') +assert.equal(resolveDeveloperReadRoot(io({ [clt]: clt }, clt)), clt) +assert.equal(resolveDeveloperReadRoot(io({ [clt]: clt }, null)), clt) +assert.equal(resolveDeveloperReadRoot(io({ [clt]: clt }, '/missing/Developer')), clt) +assert.equal(resolveDeveloperReadRoot(io({ [clt]: clt }, 'relative/Developer')), clt) +assert.equal(resolveDeveloperReadRoot(io({}, null)), null) +assert.equal(resolveDeveloperReadRoot({ ...io({ [clt]: clt }), selectedPath() { throw new Error('Unavailable') } }), clt) +assert.equal(resolveDeveloperReadRoot(io({ [selected]: '/opt/developer' })), '/opt/developer') +console.log('developer directory discovery: 9 cases passed') diff --git a/app/electron/agent/mac-developer-directory.ts b/app/electron/agent/mac-developer-directory.ts new file mode 100644 index 00000000000..8002f83c7cd --- /dev/null +++ b/app/electron/agent/mac-developer-directory.ts @@ -0,0 +1,32 @@ +import { realpathSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import path from 'node:path' + +interface DeveloperDirectoryIO { + realpath(value: string): string + selectedPath(): string | null +} + +const systemIO: DeveloperDirectoryIO = { + realpath: realpathSync, + selectedPath() { + const result = spawnSync('/usr/bin/xcode-select', ['--print-path'], { + encoding: 'utf8', timeout: 2000, env: { PATH: '/usr/bin:/bin' }, + }) + return result.status === 0 ? result.stdout.trim() : null + }, +} + +export function resolveDeveloperReadRoot(io: DeveloperDirectoryIO = systemIO): string | null { + const resolve = (value: string | null): string | null => { + if (!value || !path.isAbsolute(value)) return null + try { return io.realpath(value) } catch { return null } + } + let directory = resolve('/var/db/xcode_select_link') + if (!directory) { + try { directory = resolve(io.selectedPath()) } catch { /* retain the Command Line Tools fallback */ } + } + directory ??= resolve('/Library/Developer/CommandLineTools') + // Xcode shims also load SharedFrameworks outside Contents/Developer. + return directory?.match(/^(.*?\.app)\/Contents\/Developer$/)?.[1] ?? directory +} diff --git a/app/electron/agent/mac-sandbox-profile.ts b/app/electron/agent/mac-sandbox-profile.ts new file mode 100644 index 00000000000..600f869107a --- /dev/null +++ b/app/electron/agent/mac-sandbox-profile.ts @@ -0,0 +1,254 @@ +import { realpathSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import os from 'node:os' +import path from 'node:path' +import { resolveDeveloperReadRoot } from './mac-developer-directory' + +export type SandboxProfileId = + | 'read-only' + | 'build-test' + | 'package-install' + | 'browser' + | 'network-fetch' + | 'connector-send' + | 'system-control' + | 'untrusted-code' + +export interface SandboxProfileDefinition { + id: SandboxProfileId + label: string + allowCwdWrite: boolean + allowNetwork: boolean + envSecretsAllowed: boolean + description: string +} + +export const SANDBOX_PROFILES: Record = { + 'read-only': { + id: 'read-only', + label: 'Read-only', + allowCwdWrite: false, + allowNetwork: false, + envSecretsAllowed: false, + description: 'Read workspace files and system tools without workspace writes or network.', + }, + 'build-test': { + id: 'build-test', + label: 'Build/test', + allowCwdWrite: true, + allowNetwork: false, + envSecretsAllowed: false, + description: 'Run local builds, typechecks, tests, and git-local operations in the workspace with network denied.', + }, + 'package-install': { + id: 'package-install', + label: 'Package install', + allowCwdWrite: false, + allowNetwork: false, + envSecretsAllowed: false, + description: 'Evaluate package-install commands away from host project writes; network still requires separate policy.', + }, + browser: { + id: 'browser', + label: 'Browser', + allowCwdWrite: false, + allowNetwork: true, + envSecretsAllowed: false, + description: 'Browser/preview automation with network allowed and no workspace writes.', + }, + 'network-fetch': { + id: 'network-fetch', + label: 'Network fetch', + allowCwdWrite: false, + allowNetwork: true, + envSecretsAllowed: false, + description: 'Explicit public network fetches without workspace writes.', + }, + 'connector-send': { + id: 'connector-send', + label: 'Connector send', + allowCwdWrite: false, + allowNetwork: true, + envSecretsAllowed: false, + description: 'Approval-gated outbound connector delivery without workspace writes.', + }, + 'system-control': { + id: 'system-control', + label: 'System control', + allowCwdWrite: false, + allowNetwork: false, + envSecretsAllowed: false, + description: 'System-control commands stay isolated and approval-gated; no network or workspace writes.', + }, + 'untrusted-code': { + id: 'untrusted-code', + label: 'Untrusted code', + allowCwdWrite: false, + allowNetwork: false, + envSecretsAllowed: false, + description: 'Untrusted code interpreter profile with no network, no workspace writes, and no inherited secrets.', + }, +} + +export function sandboxProfileForCommandClass(classification: string | null | undefined): SandboxProfileId { + switch (classification) { + case 'git-read': + case 'read-only': + case 'secret-read': + return 'read-only' + case 'test': + case 'build': + case 'git-mutate': + case 'destructive-filesystem': + case 'shell': + case 'compound-shell': + case 'empty-command': + return 'build-test' + case 'package-install': + return 'package-install' + case 'network-fetch': + case 'network-shell': + return 'network-fetch' + case 'system-control': + return 'system-control' + default: + return 'untrusted-code' + } +} + +export function sandboxProfileAllowsNetwork(profile: SandboxProfileId, override?: boolean): boolean { + return override ?? SANDBOX_PROFILES[profile].allowNetwork +} + +// The global network toggle only applies to commands already classified as network-bearing. +export function taskSandboxNetworkOverride(profile: SandboxProfileId, enabled: boolean | undefined): boolean | undefined { + if (profile === 'package-install') return true + if (profile === 'network-fetch') return enabled === true + return undefined +} + +export function macSandboxProfile(cwd: string, profileOrNetwork: SandboxProfileId | boolean = 'build-test', extraReadRoots: Array = [], allowNetworkOverride?: boolean): string { + const profile = typeof profileOrNetwork === 'boolean' ? (profileOrNetwork ? 'network-fetch' : 'build-test') : profileOrNetwork + const definition = SANDBOX_PROFILES[profile] + const allowNetwork = allowNetworkOverride ?? definition.allowNetwork + const readRoots = uniqueExistingPaths([ + cwd, + '/bin', + '/sbin', + '/usr/bin', + '/usr/sbin', + '/usr/lib', + '/usr/libexec', + '/usr/share', + '/System', + '/Library', + '/opt/homebrew', + '/usr/local', + // /usr/bin/git, make, clang… are xcrun shims that load from the selected developer dir. + developerDir(), + os.tmpdir(), + process.env.TMPDIR, + darwinUserTempDir(), + ...extraReadRoots, + ]) + const writeRoots = uniqueExistingPaths([ + ...(definition.allowCwdWrite ? [cwd] : []), + os.tmpdir(), + process.env.TMPDIR, + darwinUserTempDir(), + ]) + const readRules = readRoots.map((root) => `(subpath ${sbplString(root)})`).join('\n ') + const writeRules = writeRoots.map((root) => `(subpath ${sbplString(root)})`).join('\n ') + // Deny network-adjacent mach services after the broad lookup allowance, preserving runtime and compiler access. + const machNetworkDeny = allowNetwork + ? '' + : ` +(deny mach-lookup + (global-name "com.apple.mDNSResponder") + (global-name "com.apple.mDNSResponder.dnsproxy") + (global-name "com.apple.dnssd.service") + (global-name "com.apple.SystemConfiguration.DNSConfiguration") + (global-name "com.apple.SystemConfiguration.PPPController") + (global-name "com.apple.SystemConfiguration.SCNetworkReachability") + (global-name "com.apple.SystemConfiguration.configd") + (global-name "com.apple.network.statistics") + (global-name "com.apple.networkd") + (global-name "com.apple.nehelper") + (global-name "com.apple.nesessionmanager"))` + return `(version 1) +(deny default) +(allow process*) +(allow sysctl-read) +(allow mach-lookup) +(allow ipc-posix-shm) +(allow file-map-executable) +(allow file-read-metadata) +(allow file-read-data (literal "/")) +(allow file-read* + ${readRules} + (literal "/dev/null") + (literal "/dev/random") + (literal "/dev/urandom")) +(allow file-write* + ${writeRules} + (literal "/dev/null"))${definition.allowCwdWrite ? gitControlWriteDeny(cwd) : ''}${machNetworkDeny} +${allowNetwork ? '(allow network*)' : ''}` +} + +// Deny git control-file writes at any depth because host-side git runs outside the sandbox. +export function gitControlWriteDeny(cwd: string): string { + let root: string + try { root = realpathSync(path.resolve(cwd)) } catch { return '' } + const literal = ` + (literal ${sbplString(path.join(root, '.git'))}) + (subpath ${sbplString(path.join(root, '.git', 'config'))}) + (subpath ${sbplString(path.join(root, '.git', 'config.worktree'))}) + (subpath ${sbplString(path.join(root, '.git', 'hooks'))}) + (subpath ${sbplString(path.join(root, '.git', 'info'))})` + // A quote would end the #"..." literal; such a root keeps the top-level rules only. + const nested = root.includes('"') ? '' : ` + (regex #"^${sbplRegexEscape(root)}/.+/\\.git$") + (regex #"^${sbplRegexEscape(root)}/(.+/)?\\.git/(config|config\\.worktree|hooks|info|modules/.+/(config|hooks|info))(/.*)?$")` + return ` +(deny file-write*${literal}${nested})` +} + +let cachedDeveloperDir: string | null | undefined +function developerDir(): string | null { + if (cachedDeveloperDir === undefined) cachedDeveloperDir = resolveDeveloperReadRoot() + return cachedDeveloperDir +} + +// xcrun caches lookups in DARWIN_USER_TEMP_DIR even when a scrubbed launch environment omits TMPDIR. +let cachedUserTempDir: string | null | undefined +function darwinUserTempDir(): string | null { + if (cachedUserTempDir === undefined) { + const result = process.platform === 'darwin' ? spawnSync('/usr/bin/getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8', timeout: 2000 }) : null + cachedUserTempDir = result?.status === 0 && result.stdout.trim() ? result.stdout.trim() : null + } + return cachedUserTempDir +} + +function sbplRegexEscape(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') +} + +export function uniqueExistingPaths(paths: Array): string[] { + const out: string[] = [] + const seen = new Set() + for (const item of paths) { + if (!item) continue + try { + const resolved = realpathSync(path.resolve(item)) + if (!seen.has(resolved)) { + seen.add(resolved) + out.push(resolved) + } + } catch { /* ignore missing roots */ } + } + return out +} + +export function sbplString(value: string): string { + return JSON.stringify(value) +} diff --git a/app/electron/agent/mcp-app-bundle.test.ts b/app/electron/agent/mcp-app-bundle.test.ts new file mode 100644 index 00000000000..1a3f936d8cc --- /dev/null +++ b/app/electron/agent/mcp-app-bundle.test.ts @@ -0,0 +1,90 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { createMcpServer, mcpSpawnSpec } from './mcp-process' +import { canUseMacSandbox } from './sandbox' + +function main() { + if (process.platform !== 'darwin' || !canUseMacSandbox()) { + console.log('SKIP MCP app bundle: macOS sandbox unavailable') + return + } + const compiler = spawnSync('/usr/bin/xcrun', ['--find', 'clang'], { encoding: 'utf8', timeout: 10_000 }) + const sdk = spawnSync('/usr/bin/xcrun', ['--sdk', 'macosx', '--show-sdk-path'], { encoding: 'utf8', timeout: 10_000 }) + if (compiler.status !== 0 || sdk.status !== 0) { + console.log('SKIP MCP app bundle: Xcode C compiler or macOS SDK unavailable') + return + } + // Use a private home fixture: the sandbox already permits the system temporary directories. + const root = mkdtempSync(path.join(os.homedir(), '.tensorfold-mcp-bundle-test-')) + try { + const cwd = path.join(root, 'workspace') + const contents = path.join(root, 'Fixture With Spaces.app', 'Contents') + const binary = path.join(contents, 'MacOS', 'fixture') + const library = path.join(contents, 'Frameworks', 'libfixture.dylib') + const resource = path.join(contents, 'Resources', 'fixture.txt') + const unrelated = path.join(root, 'Unrelated.app', 'Contents', 'private.txt') + for (const dir of [cwd, path.dirname(binary), path.dirname(library), path.dirname(resource), path.dirname(unrelated)]) { + mkdirSync(dir, { recursive: true }) + } + writeFileSync(resource, 'bundle resource') + writeFileSync(unrelated, 'unrelated data') + const librarySource = path.join(root, 'library.c') + const mainSource = path.join(root, 'main.c') + writeFileSync(librarySource, 'int fixture_value(void) { return 42; }\n') + writeFileSync(mainSource, [ + '#include ', + '#include ', + 'int fixture_value(void);', + 'int main(int argc, char **argv) {', + ' if (argc != 2 || strcmp(argv[1], "argument with spaces")) return 2;', + ' printf("loaded %d\\n", fixture_value());', + ' return 0;', + '}', + ].join('\n')) + for (const args of [ + ['-dynamiclib', librarySource, '-install_name', '@rpath/libfixture.dylib', '-o', library], + [mainSource, '-L', path.dirname(library), '-lfixture', '-Wl,-rpath,@executable_path/../Frameworks', '-o', binary], + ]) { + const built = spawnSync(compiler.stdout.trim(), ['-isysroot', sdk.stdout.trim(), ...args], { + encoding: 'utf8', timeout: 30_000, + }) + assert.equal(built.status, 0, built.stderr || built.error?.message) + } + const config = createMcpServer({ name: 'Bundle fixture', command: binary, args: ['argument with spaces'], cwd }) + const spec = mcpSpawnSpec(config) + assert.equal(spec.sandboxed, true) + const options = { cwd: spec.cwd, env: spec.env, encoding: 'utf8' as const, timeout: 10_000 } + const launched = spawnSync(spec.command, spec.args, options) + assert.equal(launched.status, 0, launched.stderr || launched.error?.message) + assert.equal(launched.stdout, 'loaded 42\n', 'dyld must load the sibling framework without splitting arguments') + + const probe = (script: string, file: string) => spawnSync(spec.command, [ + ...spec.args.slice(0, 2), '/bin/sh', '-c', script, 'fixture', file, + ], options) + const assertDenied = (result: ReturnType, message: string) => { + assert.ifError(result.error) + assert.equal(result.signal, null, message) + assert.ok(result.status !== null && result.status !== 0, message) + assert.match(result.stderr, /Operation not permitted|Permission denied/, message) + } + const read = probe('cat "$1"', resource) + assert.equal(read.status, 0, read.stderr) + assert.equal(read.stdout, 'bundle resource') + assertDenied(probe('cat "$1"', unrelated), 'other application bundles remain unreadable') + assertDenied(probe('printf changed > "$1"', resource), 'the selected bundle remains read-only') + assert.equal(readFileSync(resource, 'utf8'), 'bundle resource') + const argumentOnly = mcpSpawnSpec(createMcpServer({ command: '/bin/echo', args: [binary], cwd })) + const argumentRead = spawnSync(argumentOnly.command, [ + ...argumentOnly.args.slice(0, 2), '/bin/cat', resource, + ], options) + assertDenied(argumentRead, 'passing a bundle path as an argument does not grant access to its Contents') + console.log('MCP app bundle: framework loading, spaced arguments and sandbox boundaries passed') + } finally { + rmSync(root, { recursive: true, force: true }) + } +} + +main() diff --git a/app/electron/agent/mcp-process.ts b/app/electron/agent/mcp-process.ts index 90ff973a9ef..efa21186871 100644 --- a/app/electron/agent/mcp-process.ts +++ b/app/electron/agent/mcp-process.ts @@ -290,6 +290,15 @@ function mcpSandboxReadRoots(config: McpServerConfig, cwd: string): string[] { roots.push(path.dirname(path.isAbsolute(raw) ? raw : path.resolve(cwd, raw))) } add(config.command) + // dyld resolves bundled frameworks and resources outside Contents/MacOS. + if (process.platform === 'darwin') { + const executableDir = path.dirname(path.resolve(cwd, config.command)) + const contents = path.dirname(executableDir) + if (path.basename(executableDir) === 'MacOS' && path.basename(contents) === 'Contents' + && path.basename(path.dirname(contents)).endsWith('.app')) { + roots.push(contents) + } + } for (const arg of config.args) add(arg) return roots } diff --git a/app/electron/agent/sandbox.ts b/app/electron/agent/sandbox.ts index abb5cb4f2b0..12a5d366f0a 100644 --- a/app/electron/agent/sandbox.ts +++ b/app/electron/agent/sandbox.ts @@ -12,25 +12,10 @@ import { redactCommandStreams } from './command-output-redaction' import { SECRET_MASK } from './security' import { redactSecretValues } from './secret-detection' import type { ToolArtifactSummary } from './types' - -export type SandboxProfileId = - | 'read-only' - | 'build-test' - | 'package-install' - | 'browser' - | 'network-fetch' - | 'connector-send' - | 'system-control' - | 'untrusted-code' - -export interface SandboxProfileDefinition { - id: SandboxProfileId - label: string - allowCwdWrite: boolean - allowNetwork: boolean - envSecretsAllowed: boolean - description: string -} +import { SANDBOX_PROFILES, macSandboxProfile, sandboxProfileAllowsNetwork, sandboxProfileForCommandClass } from './mac-sandbox-profile' +import type { SandboxProfileId } from './mac-sandbox-profile' +export { SANDBOX_PROFILES, gitControlWriteDeny, macSandboxProfile, sandboxProfileAllowsNetwork, sandboxProfileForCommandClass, sbplString, taskSandboxNetworkOverride, uniqueExistingPaths } from './mac-sandbox-profile' +export type { SandboxProfileDefinition, SandboxProfileId } from './mac-sandbox-profile' export const SANDBOX_ARTIFACT_SCHEMA = 'vontra.sandbox-artifacts/1' @@ -147,73 +132,6 @@ const MAX_ARTIFACT_FILES = 120 const MAX_HASH_BYTES = 10 * 1024 * 1024 const SCREENSHOT_RE = /\.(?:png|jpe?g|webp|gif)$/i -export const SANDBOX_PROFILES: Record = { - 'read-only': { - id: 'read-only', - label: 'Read-only', - allowCwdWrite: false, - allowNetwork: false, - envSecretsAllowed: false, - description: 'Read workspace files and system tools without workspace writes or network.', - }, - 'build-test': { - id: 'build-test', - label: 'Build/test', - allowCwdWrite: true, - allowNetwork: false, - envSecretsAllowed: false, - description: 'Run local builds, typechecks, tests, and git-local operations in the workspace with network denied.', - }, - 'package-install': { - id: 'package-install', - label: 'Package install', - allowCwdWrite: false, - allowNetwork: false, - envSecretsAllowed: false, - description: 'Evaluate package-install commands away from host project writes; network still requires separate policy.', - }, - browser: { - id: 'browser', - label: 'Browser', - allowCwdWrite: false, - allowNetwork: true, - envSecretsAllowed: false, - description: 'Browser/preview automation with network allowed and no workspace writes.', - }, - 'network-fetch': { - id: 'network-fetch', - label: 'Network fetch', - allowCwdWrite: false, - allowNetwork: true, - envSecretsAllowed: false, - description: 'Explicit public network fetches without workspace writes.', - }, - 'connector-send': { - id: 'connector-send', - label: 'Connector send', - allowCwdWrite: false, - allowNetwork: true, - envSecretsAllowed: false, - description: 'Approval-gated outbound connector delivery without workspace writes.', - }, - 'system-control': { - id: 'system-control', - label: 'System control', - allowCwdWrite: false, - allowNetwork: false, - envSecretsAllowed: false, - description: 'System-control commands stay isolated and approval-gated; no network or workspace writes.', - }, - 'untrusted-code': { - id: 'untrusted-code', - label: 'Untrusted code', - allowCwdWrite: false, - allowNetwork: false, - envSecretsAllowed: false, - description: 'Untrusted code interpreter profile with no network, no workspace writes, and no inherited secrets.', - }, -} - export function commandNeedsNetwork(command: string): boolean { return !!commandApprovalReason(command) } @@ -224,47 +142,6 @@ export function sandboxProfileForCommand(command: string): SandboxProfileId { return sandboxProfileForCommandClass(classification) } -export function sandboxProfileForCommandClass(classification: string | null | undefined): SandboxProfileId { - switch (classification) { - case 'git-read': - case 'read-only': - case 'secret-read': - return 'read-only' - case 'test': - case 'build': - case 'git-mutate': - case 'destructive-filesystem': - case 'shell': - case 'compound-shell': - case 'empty-command': - return 'build-test' - case 'package-install': - return 'package-install' - case 'network-fetch': - case 'network-shell': - return 'network-fetch' - case 'system-control': - return 'system-control' - default: - return 'untrusted-code' - } -} - -export function sandboxProfileAllowsNetwork(profile: SandboxProfileId, override?: boolean): boolean { - return override ?? SANDBOX_PROFILES[profile].allowNetwork -} - -/** - * The global task-network toggle is only meaningful for a command already - * classified as network-bearing. It must never widen build-test/untrusted-code - * profiles merely because an opaque interpreter invocation slipped classification. - */ -export function taskSandboxNetworkOverride(profile: SandboxProfileId, enabled: boolean | undefined): boolean | undefined { - if (profile === 'package-install') return true - if (profile === 'network-fetch') return enabled === true - return undefined -} - export function captureSandboxArtifactBaseline(cwd: string, now = Date.now(), captureWorkspace = true): SandboxArtifactBaseline { const root = realpathSync(cwd) return { @@ -406,130 +283,6 @@ function prepareSandboxExecutionCwd(hostCwd: string, profile: SandboxProfileId): return realpathSync(sandboxCwd) } -export function macSandboxProfile(cwd: string, profileOrNetwork: SandboxProfileId | boolean = 'build-test', extraReadRoots: Array = [], allowNetworkOverride?: boolean): string { - const profile = typeof profileOrNetwork === 'boolean' ? (profileOrNetwork ? 'network-fetch' : 'build-test') : profileOrNetwork - const definition = SANDBOX_PROFILES[profile] - const allowNetwork = allowNetworkOverride ?? definition.allowNetwork - const readRoots = uniqueExistingPaths([ - cwd, - '/bin', - '/sbin', - '/usr/bin', - '/usr/sbin', - '/usr/lib', - '/usr/libexec', - '/usr/share', - '/System', - '/Library', - '/opt/homebrew', - '/usr/local', - // /usr/bin/git, make, clang… are xcrun shims that load from the selected developer dir. - developerDir(), - os.tmpdir(), - process.env.TMPDIR, - darwinUserTempDir(), - ...extraReadRoots, - ]) - const writeRoots = uniqueExistingPaths([ - ...(definition.allowCwdWrite ? [cwd] : []), - os.tmpdir(), - process.env.TMPDIR, - darwinUserTempDir(), - ]) - const readRules = readRoots.map((root) => `(subpath ${sbplString(root)})`).join('\n ') - const writeRules = writeRoots.map((root) => `(subpath ${sbplString(root)})`).join('\n ') - // For no-network profiles, `(allow mach-lookup)` alone would still let a sandboxed child reach - // network-resolution daemons (mDNSResponder/DNS, the system proxy/DNS configuration services) - // over the bootstrap port and perform name resolution / proxied network actions, partially - // undermining the "network denied" guarantee. SBPL is last-match-wins, so re-deny just those - // network-adjacent mach services after the broad allow — general mach-lookup (needed by dyld, - // compilers and language runtimes) stays open so build/test/read-only runs don't break. - const machNetworkDeny = allowNetwork - ? '' - : ` -(deny mach-lookup - (global-name "com.apple.mDNSResponder") - (global-name "com.apple.mDNSResponder.dnsproxy") - (global-name "com.apple.dnssd.service") - (global-name "com.apple.SystemConfiguration.DNSConfiguration") - (global-name "com.apple.SystemConfiguration.PPPController") - (global-name "com.apple.SystemConfiguration.SCNetworkReachability") - (global-name "com.apple.SystemConfiguration.configd") - (global-name "com.apple.network.statistics") - (global-name "com.apple.networkd") - (global-name "com.apple.nehelper") - (global-name "com.apple.nesessionmanager"))` - return `(version 1) -(deny default) -(allow process*) -(allow sysctl-read) -(allow mach-lookup) -(allow ipc-posix-shm) -(allow file-map-executable) -(allow file-read-metadata) -(allow file-read-data (literal "/")) -(allow file-read* - ${readRules} - (literal "/dev/null") - (literal "/dev/random") - (literal "/dev/urandom")) -(allow file-write* - ${writeRules} - (literal "/dev/null"))${definition.allowCwdWrite ? gitControlWriteDeny(cwd) : ''}${machNetworkDeny} -${allowNetwork ? '(allow network*)' : ''}` -} - -// A writable workspace still may not touch git's control files. Host-side git (status, -// diff, snapshots) runs outside the sandbox and would execute a planted core.fsmonitor, -// filter driver or hook, so a sandboxed `npm test` could otherwise escape through -// .git/config. Denies the `.git` entry itself (no swapping or creating it) and its -// config, hooks and info at any depth (nested repos, submodules). SBPL is last-match-wins. -export function gitControlWriteDeny(cwd: string): string { - let root: string - try { root = realpathSync(path.resolve(cwd)) } catch { return '' } - const literal = ` - (literal ${sbplString(path.join(root, '.git'))}) - (subpath ${sbplString(path.join(root, '.git', 'config'))}) - (subpath ${sbplString(path.join(root, '.git', 'config.worktree'))}) - (subpath ${sbplString(path.join(root, '.git', 'hooks'))}) - (subpath ${sbplString(path.join(root, '.git', 'info'))})` - // A quote would end the #"..." literal; such a root keeps the top-level rules only. - const nested = root.includes('"') ? '' : ` - (regex #"^${sbplRegexEscape(root)}/.+/\\.git$") - (regex #"^${sbplRegexEscape(root)}/(.+/)?\\.git/(config|config\\.worktree|hooks|info|modules/.+/(config|hooks|info))(/.*)?$")` - return ` -(deny file-write*${literal}${nested})` -} - -// The developer dir `xcode-select` points at (Xcode.app or the Command Line Tools), read -// from its link rather than spawning xcode-select on every sandboxed command. Inside Xcode.app -// the shims also load SharedFrameworks (DVTSystemPrerequisites), so the whole bundle is read. -let cachedDeveloperDir: string | null | undefined -function developerDir(): string | null { - if (cachedDeveloperDir === undefined) { - let dir: string | null - try { dir = realpathSync('/var/db/xcode_select_link') } catch { dir = existsSync('/Library/Developer/CommandLineTools') ? '/Library/Developer/CommandLineTools' : null } - const bundle = dir?.match(/^(.*?\.app)\/Contents\/Developer$/) - cachedDeveloperDir = bundle ? bundle[1] : dir - } - return cachedDeveloperDir -} - -// xcrun keeps its lookup cache in the per-user temp dir (confstr DARWIN_USER_TEMP_DIR), which is -// TMPDIR for a Finder launch but not when the app starts with a scrubbed environment. -let cachedUserTempDir: string | null | undefined -function darwinUserTempDir(): string | null { - if (cachedUserTempDir === undefined) { - const result = process.platform === 'darwin' ? spawnSync('/usr/bin/getconf', ['DARWIN_USER_TEMP_DIR'], { encoding: 'utf8', timeout: 2000 }) : null - cachedUserTempDir = result?.status === 0 && result.stdout.trim() ? result.stdout.trim() : null - } - return cachedUserTempDir -} - -function sbplRegexEscape(value: string): string { - return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') -} - function runShell(argv: string[], opts: { cwd: string; timeoutMs?: number; maxBuffer?: number; sandboxed: boolean; profile: SandboxedCommandResult['profile']; implementation: SandboxedCommandResult['implementation']; signal?: AbortSignal }): Promise { return new Promise((resolve) => { const [cmd, ...args] = argv @@ -832,23 +585,3 @@ function allowUnsandboxedCommands(): boolean { const value = process.env[UNSANDBOXED_ENV]?.toLowerCase() return value === '1' || value === 'true' || value === 'yes' } - -export function uniqueExistingPaths(paths: Array): string[] { - const out: string[] = [] - const seen = new Set() - for (const item of paths) { - if (!item) continue - try { - const resolved = realpathSync(path.resolve(item)) - if (!seen.has(resolved)) { - seen.add(resolved) - out.push(resolved) - } - } catch { /* ignore missing roots */ } - } - return out -} - -export function sbplString(value: string): string { - return JSON.stringify(value) -} diff --git a/app/electron/agent/setting-confirmation.test.ts b/app/electron/agent/setting-confirmation.test.ts new file mode 100644 index 00000000000..af594f401bb --- /dev/null +++ b/app/electron/agent/setting-confirmation.test.ts @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import { executeTool } from './tools' +import type { AppAction, Settings, Thread } from './types' + +const globals = globalThis as any +globals.localStorage = { getItem: () => null, setItem() {}, removeItem() {} } +globals.matchMedia = () => ({ matches: false, addEventListener() {}, removeEventListener() {} }) +globals.addEventListener = () => {}; globals.removeEventListener = () => {}; globals.window = globals +await (await import('../../src/lib/browser-demo-bootstrap')).prepareBrowserDemo() +const { api } = await import('../../src/lib/ipc') +const { useStore } = await import('../../src/lib/store') +const baseline: Settings = { ...await api.getSettings(), reasoningEffort: 'medium' } +const originalSave = api.saveSettings +let writes: Settings[] = [] +function thread(id: string): Thread { + return { id, title: id, kind: 'chat', cwd: '', providerId: 'synthetic-local', model: 'fixture', status: 'idle', + createdAt: 1, updatedAt: 1, timeline: [], apiMessages: [] } +} +function reset(action: AppAction) { + writes = [] + api.saveSettings = async (settings) => { writes.push(settings); return settings } + useStore.setState({ settings: { ...baseline }, threads: [thread('source'), thread('visible')], + status: {}, approvals: {}, view: { name: 'thread', id: 'visible' }, notice: null }) + useStore.getState().applyEvent({ type: 'item_add', runId: 'setting-fixture-run', threadId: 'source', item: { + id: 'setting-proposal', kind: 'tool', tool: 'change_setting', title: 'Change setting', appAction: action, + } }) + assert.equal(writes.length, 0, 'receiving a proposed setting must not bypass user confirmation') +} +const currentAction = () => useStore.getState().threads.find(t => t.id === 'source')!.timeline[0].appAction! + +try { + const proposal = await executeTool('change_setting', { key: 'reasoningEffort', value: 'ultrathink' }, { cwd: '/workspace' }) + assert.equal(proposal.ok, true) + assert.ok(proposal.appAction) + assert.equal(proposal.appAction.state, 'pending') + reset(proposal.appAction) + let acknowledge!: () => void + api.saveSettings = async (settings) => { + writes.push(settings) + await new Promise(resolve => { acknowledge = resolve }) + return settings + } + const pending = useStore.getState().resolveAppAction('source', 'setting-proposal', 'apply') + assert.equal(writes.length, 1, 'Apply must persist the canonical effort accepted by the actual tool') + assert.equal(writes[0].reasoningEffort, 'ultrathink') + assert.equal(currentAction().state, 'pending', 'the confirmation waits for persistence acknowledgement') + assert.equal(useStore.getState().settings?.reasoningEffort, 'medium') + acknowledge(); await pending + assert.equal(useStore.getState().settings?.reasoningEffort, 'ultrathink') + assert.equal(currentAction().state, 'applied') + assert.deepEqual(useStore.getState().view, { name: 'thread', id: 'visible' }) + assert.equal(useStore.getState().threads.find(t => t.id === 'visible')!.timeline.length, 0) + + reset({ ...proposal.appAction, payload: { key: 'reasoningEffort', value: 'ultrathinks' } }) + await useStore.getState().resolveAppAction('source', 'setting-proposal', 'apply') + assert.equal(writes.length, 0, 'an unsupported plural spelling cannot be saved from a captured action') + assert.equal(currentAction().state, 'pending') + assert.equal(useStore.getState().settings?.reasoningEffort, 'medium') + + reset(proposal.appAction) + api.saveSettings = async (settings) => { writes.push(settings); throw new Error('Synthetic persistence failure') } + await useStore.getState().resolveAppAction('source', 'setting-proposal', 'apply') + assert.equal(writes.length, 1) + assert.equal(currentAction().state, 'pending', 'a failed save must leave the proposal available to retry') + assert.equal(useStore.getState().settings?.reasoningEffort, 'medium') + assert.equal(useStore.getState().notice?.kind, 'error') + + reset(proposal.appAction) + await useStore.getState().resolveAppAction('source', 'setting-proposal', 'dismiss') + assert.equal(writes.length, 0) + assert.equal(currentAction().state, 'dismissed') + assert.equal(useStore.getState().settings?.reasoningEffort, 'medium') + console.log('Setting confirmation passed: real tool/store, persistence acknowledgement, invalid effort, failed save and dismissal.') +} finally { + api.saveSettings = originalSave +} diff --git a/app/electron/agent/tool-parallel-search.test.ts b/app/electron/agent/tool-parallel-search.test.ts index 67fe146ec7e..33b38fce27c 100644 --- a/app/electron/agent/tool-parallel-search.test.ts +++ b/app/electron/agent/tool-parallel-search.test.ts @@ -6,6 +6,7 @@ import { mock } from 'node:test' import ts from 'typescript' import { executeTool, TOOL_SCHEMAS } from './tools' import { runAgent } from './loop' +import { installDnsFixture } from './test-fixtures/dns' import type { Thread } from './types' const endpoint = 'https://search.parallel.ai/mcp' @@ -74,6 +75,7 @@ globalThis.fetch = async (input, init) => { const search = (thread: Thread, extra: Record = {}, context: any = {}) => executeTool('web_search', { query: 'public research question', provider: 'parallel', ...extra }, { cwd: '', currentThread: thread, ...context }) const calls = () => requests.filter(({ body }) => body.method === 'tools/call').map(({ body }) => body.params) +const restoreDns = installDnsFixture({ 'news.google.com': '8.8.8.8' }) try { process.env.PARALLEL_API_KEY = 'synthetic-ignored-key' for (const name of ['web_search', 'web_fetch']) { @@ -184,6 +186,7 @@ try { } finally { await new Promise((resolve) => server.close(() => resolve())) } console.log('Parallel caller checks passed: dispatch, scripted loop consumption, discovery, JSON/SSE, identity, permissions, errors, timeout and cancellation.') } finally { + restoreDns() globalThis.fetch = originalFetch delete process.env.PARALLEL_API_KEY mock.timers.reset() diff --git a/app/electron/agent/types/settings.ts b/app/electron/agent/types/settings.ts index e6fac82df24..d58238dc27c 100644 --- a/app/electron/agent/types/settings.ts +++ b/app/electron/agent/types/settings.ts @@ -182,6 +182,7 @@ export interface AgentPreset { providerId: string providerAccountId?: string | null model: string + reasoningEffort?: ReasoningEffortSetting instructions?: string approvalScope?: 'readonly' | 'review' executionTarget?: 'workspace' | 'vm' @@ -203,6 +204,7 @@ export interface BotThreadConfig { providerId: string providerAccountId: string | null model: string + reasoningEffort?: ReasoningEffortSetting approvalScope: 'readonly' | 'review' executionTarget: 'workspace' | 'vm' toolScope?: BotToolScope diff --git a/app/electron/main/host/automation-completion.ts b/app/electron/main/host/automation-completion.ts new file mode 100644 index 00000000000..61c3c0a77cf --- /dev/null +++ b/app/electron/main/host/automation-completion.ts @@ -0,0 +1,48 @@ +import { completionEvaluationRequest, evaluateCompletion, type CompletionPolicy, type CompletionVerdict } from '../../agent/automation-scheduler' +import { streamChat } from '../../agent/openai' +import { ensureTensorFoldStudioStylePrompt } from '../../agent/prompt-style' +import type { Automation, AutomationRun, Provider, ReasoningEffortSetting } from '../../agent/types' + +function completionPolicyOf(a: Automation): CompletionPolicy { + const p = a.completionPolicy + if (!p) return { type: 'none', version: 0 } + return p +} + +// Ask a fresh READ-ONLY model call to judge whether the run met its objective, using the +// run's own output as the transcript excerpt (VST-038). Only 'ai_evaluated' policies call +// a model; the rest decide deterministically. A model/parse failure degrades to +// needs_review — never a false "complete". +export async function evaluateRunCompletion(a: Automation, run: AutomationRun, provider: Provider | null, model: string | null, signal: AbortSignal, assertRequestAllowed?: () => void, reasoningEffort?: ReasoningEffortSetting): Promise<{ verdict: CompletionVerdict; reason: string } | undefined> { + const policy = completionPolicyOf(a) + if (policy.type === 'none') return undefined + let aiVerdict: CompletionVerdict | undefined + const request = completionEvaluationRequest(policy, (run.output || '').slice(-4000)) + if (request && provider && model) { + try { + assertRequestAllowed?.() + let out = '' + for await (const ch of streamChat({ + provider, baseUrl: provider.baseUrl, apiKey: provider.apiKey, model, + messages: [ + { role: 'system', content: ensureTensorFoldStudioStylePrompt('You judge whether an automation met its objective. Reply with exactly one word.') }, + { role: 'user', content: request.prompt }, + ], + temperature: 0, reasoningEffort, approvalMode: 'readonly', tools: [], signal, assertRequestAllowed, + })) { + if (ch.type === 'content') out += ch.text + } + const word = out.toLowerCase().match(/\b(complete|continue|needs_review|needs review)\b/)?.[1] + aiVerdict = word === 'complete' ? 'complete' : word === 'continue' ? 'continue' : word ? 'needs_review' : undefined + } catch { + aiVerdict = undefined // fall through to the kernel, which yields needs_review below + } + } + const result = evaluateCompletion(policy, { + iterations: 1, + signals: [], + aiVerdict: policy.type === 'ai_evaluated' ? (aiVerdict ?? 'needs_review') : undefined, + runPolicyVersion: run.permissions?.completionPolicyVersion, + }) + return { verdict: result.verdict, reason: result.reason } +} diff --git a/app/electron/main/host/automation-definition.ts b/app/electron/main/host/automation-definition.ts new file mode 100644 index 00000000000..77c341dcb21 --- /dev/null +++ b/app/electron/main/host/automation-definition.ts @@ -0,0 +1,53 @@ +import { randomUUID } from 'node:crypto' +import type { Automation } from '../../agent/types' +import { store } from '../state' +import { nextDailyAutomationRun, normalizeAutomationTimeZone } from '../../../shared/automation-time' + +export function mkAutomation(p: Partial): Automation { + return { + id: randomUUID(), + name: p.name || 'Untitled automation', + prompt: p.prompt || '', + scheduleKind: p.scheduleKind || 'manual', + everyMinutes: p.everyMinutes ?? 60, + atHour: p.atHour ?? 9, + atMinute: p.atMinute ?? 0, + ...(p.timeZone !== undefined ? { timeZone: normalizeAutomationTimeZone(p.timeZone) } : {}), + providerId: p.providerId ?? store.settings?.activeProviderId ?? null, + providerAccountId: p.providerAccountId ?? store.settings?.activeProviderAccountId ?? null, + model: p.model ?? store.settings?.activeModel ?? null, + mode: p.mode || 'chat', + cwd: p.cwd ?? store.settings?.defaultCwd ?? null, + deliverTo: p.deliverTo || 'inbox', + ...(p.deliveryTarget ? { deliveryTarget: { ...p.deliveryTarget } } : {}), + ...(p.previewOnly !== undefined ? { previewOnly: p.previewOnly } : {}), + ...(p.botId ? { botId: p.botId } : {}), + ...(p.sourceScope ? { sourceScope: p.sourceScope.map(scope => ({ ...scope })) } : {}), + ...(p.routineKind ? { routineKind: p.routineKind } : {}), + enabled: p.enabled ?? false, + lastRunAt: null, + nextRunAt: null, + lastStatus: null, + runs: [], + // Industrial fields (VST-038) carried through on create so a template / NL-built draft + // keeps its misfire policy, risk gating, and completion policy. + ...(p.misfire ? { misfire: p.misfire } : {}), + ...(p.requiredRisks ? { requiredRisks: p.requiredRisks } : {}), + ...(p.acknowledgedRisks ? { acknowledgedRisks: p.acknowledgedRisks } : {}), + ...(p.completionPolicy ? { completionPolicy: p.completionPolicy } : {}), + createdAt: Date.now(), + updatedAt: Date.now(), + } +} + +export function computeNextRun(a: Automation, from = Date.now()): number | null { + if (!a.enabled || a.scheduleKind === 'manual') return null + if (a.scheduleKind === 'interval') { + const step = Math.max(1, a.everyMinutes) * 60_000 + const base = a.lastRunAt ?? from + let next = base + step + if (next <= from) next = from + step + return next + } + return nextDailyAutomationRun(a.atHour, a.atMinute, Math.max(from, a.lastRunAt ?? from), a.timeZone) +} diff --git a/app/electron/main/host/automation-delivery.ts b/app/electron/main/host/automation-delivery.ts new file mode 100644 index 00000000000..cf365808062 --- /dev/null +++ b/app/electron/main/host/automation-delivery.ts @@ -0,0 +1,26 @@ +import { personalMessageDraftEvent } from '../../agent/tool-labels' +import { emailDraftEvent } from '../../agent/email-connector' +import type { Automation, AutomationRun, ConnectorEvent } from '../../agent/types' + +export async function deliverAutomationResult(definition: Automation, run: AutomationRun, automationId: string, rememberConnectorEvents: (events: ConnectorEvent[]) => void | Promise): Promise { + run.deliveryStatus = 'inbox' + if (definition.deliverTo !== 'inbox' && !definition.previewOnly) { + const target = definition.deliveryTarget + if (!target || target.connectorId !== definition.deliverTo || !target.recipient.trim() || (target.connectorId !== 'telegram' && !target.accountId)) { + // Existing addressless definitions remain safe/local until a user chooses a + // destination. Successful generation is not a claim of message delivery. + run.deliveryStatus = 'blocked' + run.deliveryError = 'Choose an exact account and recipient before reviewing external delivery; this result remains in the inbox.' + } else { + const event = target.connectorId === 'email' + ? emailDraftEvent({ to: target.recipient, subject: target.subject || `${definition.name} result`, body: run.output, mode: 'send' }) + : personalMessageDraftEvent({ connectorId: target.connectorId, target: target.recipient, body: run.output, accountId: target.accountId ?? undefined }) + event.approvalId = `automation-${automationId}-${run.id}` + event.payload = { ...event.payload, accountId: target.accountId, automationId: automationId, runId: run.id } + event.payloadKeys = [...event.payloadKeys, 'accountId', 'automationId', 'runId'] + await rememberConnectorEvents([event]) + run.deliveryEventId = event.id + run.deliveryStatus = 'pending_approval' + } + } +} diff --git a/app/electron/main/host/automations.ts b/app/electron/main/host/automations.ts index 24b7c10a2f8..03306b1de2c 100644 --- a/app/electron/main/host/automations.ts +++ b/app/electron/main/host/automations.ts @@ -1,10 +1,12 @@ +import { mkAutomation, computeNextRun } from './automation-definition' +import { evaluateRunCompletion } from './automation-completion' +import { deliverAutomationResult } from './automation-delivery' +import { captureBotConfig } from '../../../shared/bot-policy' import { selectedResponseLocale } from '../../agent/response-language' import { estimateTokens } from '../../agent/compaction' -import { personalMessageDraftEvent } from '../../agent/tool-labels' -import { emailDraftEvent } from '../../agent/email-connector' import { assertRoutineSources, personalRoutinePrompt, routineSourceRevision } from './personal-routine-context' import { randomUUID } from 'node:crypto' -import { automationTick, completionEvaluationRequest, evaluateCompletion, gateAutomationRun, snapshotAutomationPermissions, EMPTY_LEASE, type CompletionPolicy, type CompletionVerdict, type SchedulableAutomation, type SchedulerLease } from '../../agent/automation-scheduler' +import { automationTick, gateAutomationRun, snapshotAutomationPermissions, EMPTY_LEASE, type SchedulableAutomation, type SchedulerLease } from '../../agent/automation-scheduler' import { runAgent } from '../../agent/loop' import { streamChat } from '../../agent/openai' import { ensureTensorFoldStudioStylePrompt } from '../../agent/prompt-style' @@ -22,17 +24,7 @@ import { handle } from './ipc' import { persistAutomations } from './persistence' import { resolveWorkspaceCwd } from './workspace' import { sanitizeAutomationCreateInput, sanitizeAutomationUpdatePatch, validateAutomationProviderRoute } from './automation-patch-policy' -import { nextDailyAutomationRun, normalizeAutomationTimeZone } from '../../../shared/automation-time' -import { - modelRouteAccountLabel, - modelRouteAutoFailoverEnabled, - modelRouteResetPolicy, - modelRouter, - rememberModelRouteHistory, - routeHandoffPreview, - runtimeProviderWithFreshModels, - selectedProviderAccountId, -} from './provider-runtime' +import { modelRouteAccountLabel, modelRouteAutoFailoverEnabled, modelRouteResetPolicy, modelRouter, rememberModelRouteHistory, routeHandoffPreview, runtimeProviderWithFreshModels, selectedProviderAccountId } from './provider-runtime' export interface AutomationRunSource { trigger?: 'manual' | 'schedule' | 'webhook' | 'connector' @@ -98,55 +90,6 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation } } - function mkAutomation(p: Partial): Automation { - return { - id: randomUUID(), - name: p.name || 'Untitled automation', - prompt: p.prompt || '', - scheduleKind: p.scheduleKind || 'manual', - everyMinutes: p.everyMinutes ?? 60, - atHour: p.atHour ?? 9, - atMinute: p.atMinute ?? 0, - ...(p.timeZone !== undefined ? { timeZone: normalizeAutomationTimeZone(p.timeZone) } : {}), - providerId: p.providerId ?? store.settings?.activeProviderId ?? null, - providerAccountId: p.providerAccountId ?? store.settings?.activeProviderAccountId ?? null, - model: p.model ?? store.settings?.activeModel ?? null, - mode: p.mode || 'chat', - cwd: p.cwd ?? store.settings?.defaultCwd ?? null, - deliverTo: p.deliverTo || 'inbox', - ...(p.deliveryTarget ? { deliveryTarget: { ...p.deliveryTarget } } : {}), - ...(p.previewOnly !== undefined ? { previewOnly: p.previewOnly } : {}), - ...(p.botId ? { botId: p.botId } : {}), - ...(p.sourceScope ? { sourceScope: p.sourceScope.map(scope => ({ ...scope })) } : {}), - ...(p.routineKind ? { routineKind: p.routineKind } : {}), - enabled: p.enabled ?? false, - lastRunAt: null, - nextRunAt: null, - lastStatus: null, - runs: [], - // Industrial fields (VST-038) carried through on create so a template / NL-built draft - // keeps its misfire policy, risk gating, and completion policy. - ...(p.misfire ? { misfire: p.misfire } : {}), - ...(p.requiredRisks ? { requiredRisks: p.requiredRisks } : {}), - ...(p.acknowledgedRisks ? { acknowledgedRisks: p.acknowledgedRisks } : {}), - ...(p.completionPolicy ? { completionPolicy: p.completionPolicy } : {}), - createdAt: Date.now(), - updatedAt: Date.now(), - } - } - - function computeNextRun(a: Automation, from = Date.now()): number | null { - if (!a.enabled || a.scheduleKind === 'manual') return null - if (a.scheduleKind === 'interval') { - const step = Math.max(1, a.everyMinutes) * 60_000 - const base = a.lastRunAt ?? from - let next = base + step - if (next <= from) next = from + step - return next - } - return nextDailyAutomationRun(a.atHour, a.atMinute, Math.max(from, a.lastRunAt ?? from), a.timeZone) - } - function touchAutomation(a: Automation) { try { a.nextRunAt = computeNextRun(a); a.scheduleError = null } catch (error) { a.nextRunAt = null; a.scheduleError = error instanceof Error ? error.message : 'Fix this automation schedule before it can run.' } @@ -156,50 +99,6 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation } // The automation's completion policy as the kernel expects it (default: one pass, done). - function completionPolicyOf(a: Automation): CompletionPolicy { - const p = a.completionPolicy - if (!p) return { type: 'none', version: 0 } - return p - } - - // Ask a fresh READ-ONLY model call to judge whether the run met its objective, using the - // run's own output as the transcript excerpt (VST-038). Only 'ai_evaluated' policies call - // a model; the rest decide deterministically. A model/parse failure degrades to - // needs_review — never a false "complete". - async function evaluateRunCompletion(a: Automation, run: AutomationRun, provider: Provider | null, model: string | null, signal: AbortSignal, assertRequestAllowed?: () => void): Promise<{ verdict: CompletionVerdict; reason: string } | undefined> { - const policy = completionPolicyOf(a) - if (policy.type === 'none') return undefined - let aiVerdict: CompletionVerdict | undefined - const request = completionEvaluationRequest(policy, (run.output || '').slice(-4000)) - if (request && provider && model) { - try { - assertRequestAllowed?.() - let out = '' - for await (const ch of streamChat({ - provider, baseUrl: provider.baseUrl, apiKey: provider.apiKey, model, - messages: [ - { role: 'system', content: ensureTensorFoldStudioStylePrompt('You judge whether an automation met its objective. Reply with exactly one word.') }, - { role: 'user', content: request.prompt }, - ], - temperature: 0, approvalMode: 'readonly', tools: [], signal, assertRequestAllowed, - })) { - if (ch.type === 'content') out += ch.text - } - const word = out.toLowerCase().match(/\b(complete|continue|needs_review|needs review)\b/)?.[1] - aiVerdict = word === 'complete' ? 'complete' : word === 'continue' ? 'continue' : word ? 'needs_review' : undefined - } catch { - aiVerdict = undefined // fall through to the kernel, which yields needs_review below - } - } - const result = evaluateCompletion(policy, { - iterations: 1, - signals: [], - aiVerdict: policy.type === 'ai_evaluated' ? (aiVerdict ?? 'needs_review') : undefined, - runPolicyVersion: run.permissions?.completionPolicyVersion, - }) - return { verdict: result.verdict, reason: result.reason } - } - async function runAutomation(a: Automation, source: AutomationRunSource = {}): Promise { if (runningAutomations.has(a.id)) return const definition = structuredClone(a) @@ -257,6 +156,8 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation try { assertRoutineSources(definition, store.settings) + const capturedBot = definition.routineKind ? captureBotConfig(store.settings.agentPresets.find((bot) => bot.id === definition.botId)!, store.settings.providers) : undefined + const runReasoningEffort = () => capturedBot?.reasoningEffort ?? store.settings.reasoningEffort const context = baseProvider && definition.model ? deps.effectiveContextLimit(baseProvider, definition.model, requestedProviderAccountId) : 0 const reserve = Math.min(2_048, Math.floor(context / 3)) const maxCharacters = Math.max(0, (context - reserve - 512) * 4) @@ -293,7 +194,7 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation requestedAccountId: requestedProviderAccountId, allowFailover: !definition.routineKind && modelRouteAutoFailoverEnabled(routeBaseProvider, requestedProviderAccountId), contextLimit: deps.effectiveContextLimit(routeBaseProvider, model, requestedProviderAccountId), - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort: runReasoningEffort(), budget: definition.scheduleKind, source: 'automation_initial_route', }) @@ -352,7 +253,7 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation for await (const ch of streamChat({ provider: route.provider, baseUrl: route.provider.baseUrl, apiKey: route.provider.apiKey, model: route.model, messages, - temperature: store.settings.temperature, reasoningEffort: store.settings.reasoningEffort, approvalMode: 'readonly', tools: [], cwd: definition.routineKind ? undefined : definition.cwd || store.settings.defaultCwd || undefined, signal: controller.signal, assertRequestAllowed: definition.routineKind ? assertScopedRequest : undefined, + temperature: store.settings.temperature, reasoningEffort: runReasoningEffort(), approvalMode: 'readonly', tools: [], cwd: definition.routineKind ? undefined : definition.cwd || store.settings.defaultCwd || undefined, signal: controller.signal, assertRequestAllowed: definition.routineKind ? assertScopedRequest : undefined, })) { if (ch.type === 'content') out += ch.text beatAutomationJob() @@ -371,7 +272,7 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation await runAgent({ responseLocale: selectedResponseLocale(store.settings.uiPreferences), thread, provider: route.provider, model: route.model, approvalMode: 'readonly', temperature: store.settings.temperature, - reasoningEffort: store.settings.reasoningEffort, autoCompact: store.settings.autoCompact, contextLimit: deps.effectiveContextLimit(route.provider, route.model), + reasoningEffort: runReasoningEffort(), autoCompact: store.settings.autoCompact, contextLimit: deps.effectiveContextLimit(route.provider, route.model), toolContext: deps.fullToolContext({ thread, provider: route.provider, model: route.model, signal: controller.signal }) as any, maxSteps: 12, maxWallMs: 10 * 60_000, @@ -400,7 +301,7 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation error: err, allowFailover: !definition.routineKind && modelRouteAutoFailoverEnabled(latestBaseProvider, activeRoute.providerAccountId), contextLimit: deps.effectiveContextLimit(latestBaseProvider, activeRoute.model, activeRoute.providerAccountId), - reasoningEffort: store.settings.reasoningEffort, + reasoningEffort: runReasoningEffort(), budget: definition.scheduleKind, source: 'automation_recovery', }) @@ -452,33 +353,14 @@ export function createAutomationRuntime(deps: AutomationRuntimeDeps): Automation // run's output as the transcript excerpt to a fresh, read-only model call and record // its one-word verdict; deterministic policies evaluate without a model. The version // guard forces needs_review if the policy was edited after this run started. - run.completion = await evaluateRunCompletion(definition, run, provider, model, controller.signal, definition.routineKind ? () => assertRoutineRequest(provider ?? undefined) : undefined) + run.completion = await evaluateRunCompletion(definition, run, provider, model, controller.signal, definition.routineKind ? () => assertRoutineRequest(provider ?? undefined) : undefined, capturedBot?.reasoningEffort) if ((a.completionPolicy?.version ?? 0) !== (definition.completionPolicy?.version ?? 0)) run.completion = { verdict: 'needs_review', reason: 'Completion policy changed during this run; review the result.' } assertRoutineRequest(provider ?? undefined) if (controller.signal.aborted) throw new Error('Automation cancelled before completion.') run.status = 'ok' a.lastStatus = 'ok' deps.finishJob(job, 'completed') - run.deliveryStatus = 'inbox' - if (definition.deliverTo !== 'inbox' && !definition.previewOnly) { - const target = definition.deliveryTarget - if (!target || target.connectorId !== definition.deliverTo || !target.recipient.trim() || (target.connectorId !== 'telegram' && !target.accountId)) { - // Existing addressless definitions remain safe/local until a user chooses a - // destination. Successful generation is not a claim of message delivery. - run.deliveryStatus = 'blocked' - run.deliveryError = 'Choose an exact account and recipient before reviewing external delivery; this result remains in the inbox.' - } else { - const event = target.connectorId === 'email' - ? emailDraftEvent({ to: target.recipient, subject: target.subject || `${definition.name} result`, body: run.output, mode: 'send' }) - : personalMessageDraftEvent({ connectorId: target.connectorId, target: target.recipient, body: run.output, accountId: target.accountId ?? undefined }) - event.approvalId = `automation-${a.id}-${run.id}` - event.payload = { ...event.payload, accountId: target.accountId, automationId: a.id, runId: run.id } - event.payloadKeys = [...event.payloadKeys, 'accountId', 'automationId', 'runId'] - await deps.rememberConnectorEvents([event]) - run.deliveryEventId = event.id - run.deliveryStatus = 'pending_approval' - } - } + await deliverAutomationResult(definition, run, a.id, deps.rememberConnectorEvents) } catch (e: any) { const settlement = automationRunError(e, controller.signal.aborted) diff --git a/app/electron/main/host/bot-reasoning-runtime.test.ts b/app/electron/main/host/bot-reasoning-runtime.test.ts new file mode 100644 index 00000000000..fc5d78eafce --- /dev/null +++ b/app/electron/main/host/bot-reasoning-runtime.test.ts @@ -0,0 +1,95 @@ +import assert from 'node:assert/strict' +import { createServer } from 'node:http' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { captureBotConfig } from '../../../shared/bot-policy' +import { buildPersonalRoutine } from '../../../shared/personal-routines' +import type { AgentPreset, Job, Provider, Thread } from '../../agent/types' + +const profile = await fs.mkdtemp(path.join(os.tmpdir(), 'tensorfold-bot-effort-runtime-')) +const previousHome = process.env.VONTRA_HOME +process.env.VONTRA_HOME = profile +const requests: Record[] = [] +const server = createServer((request, response) => { + if (request.method === 'GET') { + response.writeHead(200, { 'Content-Type': 'application/json' }) + response.end(JSON.stringify({ data: [{ id: 'fixture', object: 'model' }] })) + return + } + let raw = '' + request.on('data', (chunk) => { raw += chunk }) + request.on('end', () => { + requests.push(JSON.parse(raw)) + response.writeHead(200, { 'Content-Type': 'text/event-stream' }) + response.end(`data: ${JSON.stringify({ choices: [{ delta: { content: 'Synthetic review complete.' }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`) + }) +}) +await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) +try { + const { defaultSettings, saveThreads } = await import('../../store') + const { store } = await import('../state') + const { createThreadRuntime } = await import('./thread-runtime') + const { WorkspaceMutationGuard } = await import('./workspace-mutation-guard') + const { compactThreadJournal } = await import('../../agent/thread-journal') + const { createAutomationRuntime } = await import('./automations') + const provider: Provider = { id: 'effort-fixture', name: 'Local fixture', kind: 'local', transport: 'chat-completions', baseUrl: `http://127.0.0.1:${(server.address() as any).port}/v1`, apiKey: '', models: ['fixture'] } + const preset: AgentPreset = { id: 'bot_effort', name: 'Reviewer', role: 'Review supplied text', lane: 'review', providerId: provider.id, model: 'fixture', reasoningEffort: 'low', toolScope: { mode: 'selected', names: [] }, createdAt: 1, updatedAt: 1 } + const captured = captureBotConfig(preset, [provider]) + store.settings = { ...defaultSettings(), providers: [provider], agentPresets: [{ ...preset, reasoningEffort: 'high' }], activeProviderId: provider.id, activeModel: 'fixture', reasoningEffort: 'high', autoCompact: false } + const makeThread = (id: string, bot = captured): Thread => ({ id, title: 'Synthetic review', kind: 'chat', cwd: '', providerId: provider.id, providerAccountId: null, model: 'fixture', bot, createdAt: 1, updatedAt: 1, status: 'idle', apiMessages: [], timeline: [] }) + store.threads = [makeThread('captured-low'), makeThread('captured-high', { ...captured, reasoningEffort: 'high' }), makeThread('legacy', { ...captured, reasoningEffort: undefined })] + await saveThreads(store.threads) + const aborters = new Map() + let settled: (outcome: string) => void = () => {} + const runtime = createThreadRuntime({ + aborters, workspaceMutationGuard: new WorkspaceMutationGuard(), pendingApprovalMeta: new Map(), jobLeaseOwner: 'fixture', threadJobHeartbeatMs: 5000, + sshManager: { ensureConnected: async () => {} }, emitToRenderer() {}, persistThreads() {}, + fullToolContext: ({ thread } = {}) => ({ cwd: profile, currentThread: thread }), approvalResolver: () => async () => 'deny', isHighRiskTool: () => false, + claimJob: () => ({ id: 'fixture-job', status: 'running' } as Job), patchJob: (job) => job, replaceJobResult: (result) => result.job!, heartbeatJob: (job) => job, + settleThreadRunJob: (_job, _thread, outcome) => settled(outcome), renderProjectMemoryBucket: () => '', effectiveContextLimit: () => 8192, + }) + for (const [id, globalEffort, expected] of [['captured-low', 'high', 'low'], ['captured-high', 'low', 'high'], ['legacy', 'high', 'high']] as const) { + store.settings.reasoningEffort = globalEffort + let timer: ReturnType | undefined + const finished = new Promise((resolve, reject) => { + settled = resolve + timer = setTimeout(() => { runtime.cancelThreadRun(id); reject(new Error('Synthetic bot run did not settle.')) }, 10_000) + }) + try { + await runtime.startThreadRun({ threadId: id, userText: 'Review this synthetic text.' }) + const outcome = await finished + assert.equal(outcome, 'completed', JSON.stringify(store.threads.find((thread) => thread.id === id)?.timeline)) + assert.equal(requests.at(-1)?.reasoning_effort, expected, `${id} sends its captured effort through the actual host and HTTP request`) + assert.equal(aborters.size, 0) + } finally { + clearTimeout(timer) + await compactThreadJournal(path.join(profile, 'thread-journals'), id, 1).catch(() => {}) + } + } + let afterCapture = () => {} + const automations = createAutomationRuntime({ + threadJobHeartbeatMs: 5000, claimJob: () => ({ id: 'routine-job' } as Job), patchJob: (job) => job, heartbeatJob: (job) => job, finishJob() {}, emitAutomation() {}, + effectiveContextLimit: () => { afterCapture(); return 8192 }, fullToolContext: () => { throw new Error('Personal routines must not request global tools.') }, + applyEventToThread: runtime.applyEventToThread, timelineErrorSince: runtime.timelineErrorSince, timelineError: runtime.timelineError, + isHighRiskTool: () => false, rememberConnectorEvents: () => { throw new Error('Preview routines must not deliver external messages.') }, + }) + for (const [savedEffort, globalEffort, expected] of [['low', 'high', 'low'], ['high', 'low', 'high'], [undefined, 'high', 'high']] as const) { + store.settings.agentPresets[0].reasoningEffort = savedEffort + store.settings.reasoningEffort = globalEffort + afterCapture = () => { store.settings.agentPresets[0].reasoningEffort = 'medium' } + const routine = automations.mkAutomation(buildPersonalRoutine({ kind: 'morning-brief', botId: preset.id, providerId: provider.id, model: 'fixture', sourceScope: [], timeZone: 'Etc/UTC' })) + await automations.runAutomation(routine) + assert.equal(routine.runs[0].status, 'ok', routine.runs[0].error ?? '') + assert.equal(requests.at(-1)?.reasoning_effort, expected, 'a routine captures its bot effort before startup awaits or preset edits') + } + assert.equal(requests.length, 6) + console.log('Actual bot/routine host and HTTP checks passed: independent captured efforts, preset edits and legacy fallback.') +} finally { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + await (await import('./persistence')).preserveStateForUpdate() + if (previousHome === undefined) delete process.env.VONTRA_HOME + else process.env.VONTRA_HOME = previousHome + await fs.rm(profile, { recursive: true, force: true, maxRetries: 5, retryDelay: 30 }) +} diff --git a/app/electron/main/host/local-delete-archive.test.ts b/app/electron/main/host/local-delete-archive.test.ts index f03352a2c03..8b722c8b494 100644 --- a/app/electron/main/host/local-delete-archive.test.ts +++ b/app/electron/main/host/local-delete-archive.test.ts @@ -96,8 +96,8 @@ assert.match(archive, /controls\.publish\?\.\('ticket'/, 'archive publishes tick assert.match(archive, /Restore the active parent project before restoring linked tickets/, 'ticket restore cannot create an active orphan under archived parents') assert.match(archive, /Restore the active linked thread in the same project/, 'ticket restore cannot reactivate against an archived or cross-project linked thread') -const threadRuntime = source('./thread-runtime.ts') -const threadStart = threadRuntime.slice(threadRuntime.indexOf('async function startThreadRun'), threadRuntime.indexOf('\n function applyEventToThread')) +const threadRuntime = source('./thread-run-start.ts') +const threadStart = threadRuntime.slice(threadRuntime.indexOf('async function startThreadRun'), threadRuntime.indexOf('\n return startThreadRun')) assert.match(threadStart, /thread\.archivedAt/, 'thread start rejects archived records') assert.match(threadStart, /project\.archivedAt/, 'thread start rejects an archived parent project') assert.ok(threadStart.indexOf('reserveStart') < threadStart.indexOf('aborters.set'), 'thread run lease is acquired before its aborter/start reservation') diff --git a/app/electron/main/host/project-memory-trash-consumers.test.ts b/app/electron/main/host/project-memory-trash-consumers.test.ts index efdd33f8c87..0a0c68ad84f 100644 --- a/app/electron/main/host/project-memory-trash-consumers.test.ts +++ b/app/electron/main/host/project-memory-trash-consumers.test.ts @@ -40,7 +40,7 @@ const runtime = createToolContextRuntime({ // Execute the production nested functions with inert persistence collaborators, avoiding a model run. async function productionMemoryCallbacks(thread: Thread) { - const source = await readFile(new URL('./thread-runtime.ts', import.meta.url), 'utf8') + const source = (await Promise.all(['./thread-runtime.ts', './thread-run-execution.ts'].map((file) => readFile(new URL(file, import.meta.url), 'utf8')))).join('\n') const tree = ts.createSourceFile('thread-runtime.ts', source, ts.ScriptTarget.Latest, true) let postRun: ts.FunctionDeclaration | undefined, compaction: ts.ArrowFunction | undefined function visit(node: ts.Node) { diff --git a/app/electron/main/host/room-ticket-patch-policy.test.ts b/app/electron/main/host/room-ticket-patch-policy.test.ts index dfc7acf2e83..1b56653ee73 100644 --- a/app/electron/main/host/room-ticket-patch-policy.test.ts +++ b/app/electron/main/host/room-ticket-patch-policy.test.ts @@ -50,7 +50,7 @@ assert.deepEqual(steer, { id: 'steer-1', tick: 5, kind: 'user', seat: 'you', tar assert.equal(steerRoom.events.at(-1), steer) assert.throws(() => appendRoomSteeringEvent({ ...steerRoom, state: 'ready' }, 'wait', () => 'x'), /Start the room/) -assert.deepEqual({ ...pickTicketUserPatch({ status: 'ready', roomId: 'room-1' }) }, { status: 'ready', roomId: 'room-1' }) +assert.deepEqual({ ...pickTicketUserPatch({ status: 'ready', roomId: 'room-1' }) }, { status: 'ready', roomId: 'room-1', assignee: null }) for (const field of ['threadId', 'runState', 'startedAt', 'execution', 'evidence', 'assignee', 'orchestratorHostId']) { assert.throws(() => pickTicketUserPatch({ [field]: null }), new RegExp(`${field} cannot be changed`)) } diff --git a/app/electron/main/host/room-ticket-patch-policy.ts b/app/electron/main/host/room-ticket-patch-policy.ts index c25dfed184c..acf7b28864a 100644 --- a/app/electron/main/host/room-ticket-patch-policy.ts +++ b/app/electron/main/host/room-ticket-patch-policy.ts @@ -251,6 +251,7 @@ export function pickTicketUserPatch(input: unknown): Partial { if (Object.prototype.hasOwnProperty.call(patch, 'dependsOn')) assertStringList(patch.dependsOn, 'dependsOn', 64, 256) if (Object.prototype.hasOwnProperty.call(patch, 'dependencyFailurePolicy')) assertEnum(patch.dependencyFailurePolicy, TICKET_DEPENDENCY_FAILURE_POLICIES, 'dependencyFailurePolicy') if (Object.prototype.hasOwnProperty.call(patch, 'order') && (typeof patch.order !== 'number' || !Number.isFinite(patch.order))) throw new Error('order must be a finite number.') + if (patch.status === 'ready') patch.assignee = null return patch } diff --git a/app/electron/main/host/thread-journal-crypto.ts b/app/electron/main/host/thread-journal-crypto.ts new file mode 100644 index 00000000000..08d65271ed5 --- /dev/null +++ b/app/electron/main/host/thread-journal-crypto.ts @@ -0,0 +1,52 @@ +import { encryptWithKey, decryptWithKey, resolveLocalSecretKeySync } from '../../local-crypto' +import { vontraPath } from '../../store' + +// Per-thread NDJSON journals hold the FULL transcript (messages, tool args, tool output, +// diffs) — the most sensitive data in the app. threads.json is encrypted at rest via +// writeProtectedJson, so writing the journal as plaintext NDJSON defeats the same +// at-rest posture (local-crypto.ts: casual disk reads / accidental settings-dir sharing). +// We encrypt each journal event with the same app key, keeping the {seq, ts} envelope in +// the clear so compaction (which only reads seq) keeps working without a key. +const JOURNAL_ENC_PREFIX = 'enc:v1:' + +// Lazily resolve the same primary/fallback keys as store.ts. Failure disables the +// best-effort journal; it must never downgrade a full transcript to plaintext. +let cachedJournalKey: Buffer | null = null +export function journalKey(): Buffer | null { + if (cachedJournalKey) return cachedJournalKey + try { + cachedJournalKey = resolveLocalSecretKeySync(vontraPath('.secretkey')).key + return cachedJournalKey + } catch { + return null + } +} + +// Wrap an AgentEvent for the journal: encrypt its JSON with the app key when available, +// emitting { e: 'enc:v1:' }. If crypto is unavailable, return null so +// the caller skips this optional journal rather than leaking the event verbatim. +export function encodeJournalEvent(event: unknown, key: Buffer | null): unknown | null { + if (!key) return null + try { + return { e: JOURNAL_ENC_PREFIX + encryptWithKey(JSON.stringify(event), key) } + } catch { + return null + } +} + +// Inverse of encodeJournalEvent: decrypt an encrypted journal envelope back to the +// original event, tolerating legacy/plaintext lines written before encryption existed. +export function decodeJournalEvent(stored: unknown, key: Buffer | null): unknown { + if (stored && typeof stored === 'object' && typeof (stored as { e?: unknown }).e === 'string') { + const payload = (stored as { e: string }).e + if (payload.startsWith(JOURNAL_ENC_PREFIX)) { + if (!key) return null // cannot decrypt without the key + try { + return JSON.parse(decryptWithKey(payload.slice(JOURNAL_ENC_PREFIX.length), key)) + } catch { + return null // wrong key / tampered / corrupt + } + } + } + return stored // legacy plaintext event written before journal encryption +} diff --git a/app/electron/main/host/thread-run-execution.ts b/app/electron/main/host/thread-run-execution.ts new file mode 100644 index 00000000000..fc21123f1a9 --- /dev/null +++ b/app/electron/main/host/thread-run-execution.ts @@ -0,0 +1,253 @@ +import { selectedResponseLocale } from '../../agent/response-language' +import { RunRecoveryTracker } from '../../agent/run-recovery/tracker' +import { assertThreadMemoryTransport, canContributeThreadMemory } from '../../../shared/thread-memory-policy' +import { assertGoogleContextTransport } from '../../../shared/google-workspace-privacy' +import { randomUUID } from 'node:crypto' +import { runAgent } from '../../agent/loop' +import { runOmpThread } from '../../agent/omp-engine' +import { assertOmpEngineAllowed } from '../../agent/planning-guard' +import { executeTool, isReadOnlyTool } from '../../agent/tools' +import { createSubAgentFromLaunch, parentForThread, updateSubAgent } from '../../agent/subagents' +import { saveSubAgents } from '../../store' +import { selectChannelPrompt } from '../../agent/channel-prompt' +import { resolvePersona, personaSystemBlock } from '../../agent/persona' +import { createProjectMemoryCandidate } from '../../agent/project-memory' +import { projectMemoryAutoCandidateTurn, projectMemoryAutoMessages } from './project-memory-auto-policy' +import { persistProjectMemoryCandidates } from './persistence' +import { auditPreview } from '../../agent/security' +import type { AgentEvent, Provider, StartRunPayload, Thread, WorkspaceLocation } from '../../agent/types' +import { store } from '../state' +import { auditEvent } from './audit' +import { botInstructions, botRunApprovalMode } from '../../../shared/bot-policy' +import { scopeBotToolContext } from '../../agent/bot-tool-scope' +import { createBotVmToolContext, getBotVmHost } from './bot-vm-host' +import { assertBotLifecycleIdle } from './bot-run-boundary' +import { getUserQuestionHost } from './user-question-host' +import { isExternalProvider } from '../../../shared/provider-trust' +import { INCOGNITO_PERSISTENT_TOOLS } from '../../agent/incognito' +import { PluginRuntime } from '../../agent/plugin-runtime' +import type { UserQuestionInput, UserQuestionRun } from '../../agent/types' + +import type { ApprovalMode, ThreadMemoryPolicy } from '../../agent/types' +import type { ThreadRuntimeDeps, ThreadRunAdmission, JobHandle } from './thread-runtime' +import type { ThreadRunSupport } from './thread-run-start' +import { assertIncognitoThreadTransportSupported, assertSshToolContextConnected } from './thread-run-policy' +import { botRunReasoningEffort } from '../../../shared/bot-reasoning' + +export interface ThreadRoute { provider: Provider; providerAccountId: string | null; model: string } +export interface ThreadRunReview { viewedSkillNames: Set; provider: Provider | null; model: string } +export interface ThreadRouteContext { + deps: ThreadRuntimeDeps + support: ThreadRunSupport + thread: Thread + controller: AbortController + admission?: ThreadRunAdmission + botVm: boolean + restrictedBot: boolean + vmHost: ReturnType + workspace: WorkspaceLocation | null + memoryPolicy: ThreadMemoryPolicy + memoryRevision: number + runId: string + runApprovalMode: ApprovalMode + runContract: NonNullable + runMaxWallMs: number + localHelpersOnly: boolean + payload: StartRunPayload + jobHandle: JobHandle + review: ThreadRunReview + assertBotResearchOff(provider: Provider | undefined): void + emit(event: AgentEvent): void +} + +export function createThreadRouteRunner(input: ThreadRouteContext) { + const { deps, support, thread, controller, admission, botVm, restrictedBot, vmHost, workspace, memoryPolicy, memoryRevision, runId, runApprovalMode, runContract, runMaxWallMs, localHelpersOnly, payload, jobHandle, review, assertBotResearchOff, emit } = input + const { aborters, threadJobHeartbeatMs, emitToRenderer, persistThreads, fullToolContext, approvalResolver, isHighRiskTool, heartbeatJob, renderProjectMemoryBucket, effectiveContextLimit } = deps + const { drainThreadCues, waitForThreadCue, timelineErrorSince, timelineError } = support + const routeProviderForModel = (routeProvider: Provider, routeModel: string, runModel: string) => + runModel === routeModel ? routeProvider : { ...routeProvider, models: [runModel, ...routeProvider.models.filter((candidate) => candidate !== runModel)] } + + const runWithRoute = async (route: { provider: Provider; providerAccountId: string | null; model: string }, runModel = route.model) => { + const providerAccountId = route.providerAccountId + admission?.assertAllowed() + const timelineStart = thread.timeline.length + const activeProvider = routeProviderForModel(route.provider, route.model, runModel) + assertGoogleContextTransport(thread, activeProvider) + assertIncognitoThreadTransportSupported(thread, activeProvider) + if (thread.bot) { + assertBotLifecycleIdle(thread.bot.presetId) + botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) + if (botVm || restrictedBot) assertBotResearchOff(activeProvider) + } + review.provider = activeProvider + review.model = runModel + let lastJobBeat = Date.now() + const beatThreadJob = () => { + if (Date.now() - lastJobBeat < threadJobHeartbeatMs) return + lastJobBeat = Date.now() + jobHandle.set(heartbeatJob(jobHandle.get()) ?? jobHandle.get()) + } + // Provider/route discovery above can take long enough for an SSH session to drop. + // Capture the tool context once at the final execution seam, validate that exact + // snapshot, and pass it through unchanged. Re-resolving later (or accepting an + // undefined backend) could reinterpret the remote path as a local lookalike. + if (thread.bot && (activeProvider.id !== thread.bot.providerId || route.providerAccountId !== thread.bot.providerAccountId || runModel !== thread.bot.model)) throw new Error('Bots keep their captured model and account; start a new bot chat to change them.') + const baseToolContext = botVm ? { cwd: '/workspace', signal: controller.signal, currentThread: thread } : fullToolContext({ thread, provider: activeProvider, model: runModel, signal: controller.signal, memoryPolicy }) + const toolContext = scopeBotToolContext(thread.bot, botVm ? createBotVmToolContext(vmHost!, thread.bot!.presetId, baseToolContext) : baseToolContext) + toolContext.memoryPolicy = memoryPolicy + assertThreadMemoryTransport(thread, activeProvider, memoryPolicy) + if (restrictedBot) toolContext.botToolScopeGuard = () => { + assertBotLifecycleIdle(thread.bot!.presetId) + botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) + assertBotResearchOff(activeProvider) + } + if (thread.incognito) toolContext.disabledToolNames = [...new Set([...toolContext.disabledToolNames ?? [], ...INCOGNITO_PERSISTENT_TOOLS])] + if (botVm) toolContext.botVm!.assertModelPrivacy = () => { + assertBotLifecycleIdle(thread.bot!.presetId) + botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) + assertBotResearchOff(activeProvider) + } + assertSshToolContextConnected(workspace, toolContext) + const questions = getUserQuestionHost() + if (questions && thread.engine !== 'omp' && !isExternalProvider(activeProvider) && (!activeProvider.transport || activeProvider.transport === 'chat-completions')) { + toolContext.askUser = (input: UserQuestionInput, run: UserQuestionRun) => questions.ask(input, { ...run, threadId: thread.id, runId }) + } + // OMP engine threads (VST-050) run ON the installed omp coding agent via its + // headless rpc mode: omp owns the agent loop, TensorFold mirrors the timeline, plan, + // subagents, and Guide steering. The native loop below stays the default. + if (thread.engine === 'omp') { + assertOmpEngineAllowed() + const delegated = new RunRecoveryTracker(runId, snapshot => { + if (aborters.get(thread.id) !== controller) return + thread.runRecovery = snapshot; persistThreads() + emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { runRecovery: snapshot } }) + }) + const activeTools = new Set>() + let acceptingTools = true, delegatedComplete = false + const stopDelegated = () => delegated.stopRequested() + delegated.start(); delegated.begin('delegated'); delegated.requestStarted() + controller.signal.addEventListener('abort', stopDelegated, { once: true }) + try { await runOmpThread({ + thread, + runId, + emit: (event) => { emit(event); beatThreadJob() }, + signal: controller.signal, + persist: persistThreads, + userText: payload.userText, + approvalMode: runApprovalMode, + reasoningEffort: botRunReasoningEffort(thread, store.settings.reasoningEffort), + drainCues: () => drainThreadCues(thread.id), + onSession: (cursor) => { thread.ompResumeCursor = cursor }, + // Host-tools bridge: omp's model plans, TensorFold's approval gate and executor + // own every mutation (write_file/edit_file/apply_patch/run_command). + requestApproval: approvalResolver(controller, jobHandle), + executeTool: async (name, args) => { + if (!acceptingTools) throw new Error('The delegated run is stopping; no further tools can start.') + const operation = randomUUID(), mutating = !isReadOnlyTool(name) + delegated.begin(operation, mutating) + const pending = executeTool(name, args, { ...toolContext, currentThread: thread, signal: controller.signal }) + activeTools.add(pending) + try { const result = await pending; delegated.toolCompleted(mutating, result.ok); return result } + catch (error) { if (mutating) delegated.toolUncertain(); throw error } + finally { activeTools.delete(pending); delegated.end(operation) } + }, + updateSubAgent: (record) => { + const existing = store.subAgents.find((agent) => agent.id === record.id) + if (existing) { + const updated = updateSubAgent(store.subAgents, record.id, { status: record.status, name: record.name, task: record.task }) + if (updated.agent) store.subAgents = updated.agents + } else { + const created = createSubAgentFromLaunch(store.subAgents, { + source: 'thread_tool', + parent: parentForThread(thread), + task: record.task, + name: record.name, + providerId: activeProvider.id, + providerAccountId, + model: runModel, + runId: `omp-${record.id}`, + cwd: thread.cwd, + }) + // omp mints its own stable subagent ids; keep them as the TensorFold ids so + // later snapshots update the same records. + created.agent.id = record.id + store.subAgents = created.agents + } + void saveSubAgents(store.subAgents) + }, + }); delegated.requestComplete(); delegatedComplete = true + } catch (error) { delegated.requestFailed('unknown'); throw error } + finally { + acceptingTools = false + await Promise.allSettled([...activeTools]) + delegated.end('delegated'); delegated.settle(delegatedComplete) + controller.signal.removeEventListener('abort', stopDelegated) + } + } else { + await runAgent({ + responseLocale: selectedResponseLocale(store.settings.uiPreferences), + onRecovery: snapshot => { + if (aborters.get(thread.id) !== controller) return + thread.runRecovery = snapshot + persistThreads() + emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { runRecovery: snapshot } }) + }, + assertRequestAllowed: () => { admission?.assertAllowed(); assertGoogleContextTransport(thread, activeProvider) }, + thread, + provider: activeProvider, + model: runModel, + runId, + approvalMode: runApprovalMode, + temperature: store.settings.temperature, + reasoningEffort: botRunReasoningEffort(thread, store.settings.reasoningEffort), + serviceTier: store.settings.serviceTier, + autoCompact: store.settings.autoCompact, + contextLimit: effectiveContextLimit(activeProvider, runModel), + toolContext, + observe: thread.incognito ? undefined : deps.observe, + pluginRuntime: thread.incognito ? new PluginRuntime() : undefined, + drainCues: () => drainThreadCues(thread.id), + waitForCue: (timeoutMs, signal) => waitForThreadCue(thread.id, timeoutMs, signal), + memoryPolicy, + projectMemory: botVm || !memoryPolicy.useExisting ? '' : renderProjectMemoryBucket(store.projects.find((p) => p.id === thread.projectId), payload.userText), + // Resolve the persona fresh each run (hot reload) for this thread's scope. + personaBlock: thread.bot ? botInstructions(thread.bot) : personaSystemBlock( + resolvePersona(store.settings.personas ?? [], { isAssistant: thread.kind === 'chat', workspaceId: thread.projectId ?? null }), + { userProfile: store.settings.userProfile }, + ), + // Per-channel ephemeral prompt: when this run acts on a connector conversation, inject + // that source's channelPrompt for this run only (never into the persisted snapshot). + channelPrompt: selectChannelPrompt(payload.sourceThreadKey, store.settings) ?? undefined, + // File durable facts salvaged at compaction as pending project-memory candidates + // (project-scoped; skipped for project-less chat threads). + onMemoryHarvest: (candidates) => { + if (thread.googleLocalOnly || !canContributeThreadMemory(thread, memoryPolicy, memoryRevision, controller.signal) || !store.threads.includes(thread) || !thread.projectId || !candidates.length) return + const authored = projectMemoryAutoMessages(store.projectMemory, thread) + for (const text of candidates) { + const sourceTurn = projectMemoryAutoCandidateTurn(authored, text) + if (sourceTurn === null) continue + store.projectMemoryCandidates = [createProjectMemoryCandidate({ projectId: thread.projectId, text, sourceType: 'agent', reason: 'Salvaged from the conversation at compaction.', sourceThreadId: thread.id, sourceTurn }), ...store.projectMemoryCandidates] + } + persistProjectMemoryCandidates() + }, + onProviderRateLimits: deps.recordProviderRateLimits, + guardPolicy: runContract.guardPolicy, + maxSteps: runContract.guardPolicy.maxSteps, + maxWallMs: runMaxWallMs, + emit: (event) => { emit(event); beatThreadJob() }, + signal: controller.signal, + requestApproval: approvalResolver(controller, jobHandle), + auditToolCall: async ({ tool, args, resultOk, output }) => { + // Note skills the agent actually read this run — the post-run review only looks at these. + if (tool === 'skill_view' && resultOk && args?.name) review.viewedSkillNames.add(String(args.name)) + if (isHighRiskTool(tool)) await auditEvent('agent.tool', { threadId: thread.id, runId, tool, ok: resultOk, ...(thread.incognito ? {} : { cwd: auditPreview(thread.cwd), args: auditPreview(JSON.stringify(args)), output: auditPreview(output) }) }) + }, + persist: persistThreads, + }) + } + const errorItem = timelineErrorSince(thread, timelineStart) + if (errorItem && !controller.signal.aborted) throw timelineError(errorItem) + } + + return runWithRoute +} diff --git a/app/electron/main/host/thread-run-policy.ts b/app/electron/main/host/thread-run-policy.ts new file mode 100644 index 00000000000..7166d0dced8 --- /dev/null +++ b/app/electron/main/host/thread-run-policy.ts @@ -0,0 +1,56 @@ +import type { Provider, Thread, WorkspaceLocation } from '../../agent/types' +import type { ThreadRuntimeDeps } from './thread-runtime' +import { resolveWorkspaceCwd } from './workspace' +import { resolvePairedWorkspace } from '../../agent/local-workspace-policy' + +export async function recordPreTurnCheckpoint(input: { + threadId: string + incognito?: boolean + turn: number + target: { cwd?: string | null; workspace?: WorkspaceLocation | null; kind?: Thread['kind'] } + conversation: { apiMessages: unknown[]; timeline: unknown[]; goal?: string; goalStatus?: string; plan?: unknown[]; status?: string } +}, deps: Pick): Promise { + if (input.incognito) return + let fileSha: string | null = null + if (deps.captureCheckpoint && input.target.kind !== 'chat') { + try { + const captured = await deps.captureCheckpoint(input.threadId, input.turn, input.target) + if (captured.ok && captured.sha) fileSha = captured.sha + } catch { /* file checkpoints are best-effort; still retain the conversation snapshot */ } + } + try { deps.recordTurnCheckpoint?.(input.threadId, input.turn, input.conversation, fileSha) } catch { /* best effort */ } +} + +export async function resolveThreadRunCwd(thread: Pick, workspace: WorkspaceLocation | null, boundary = thread.workspaceBoundary): Promise { + if (thread.kind === 'chat') return thread.cwd + if (boundary === 'home') return resolvePairedWorkspace(thread.cwd, workspace) + if (workspace?.kind === 'ssh') { + const remotePath = String(workspace.path || '').trim() + if (!remotePath) throw new Error('Choose a remote workspace folder before running workspace tools.') + return remotePath + } + const localPath = workspace?.kind === 'local' && workspace.path ? workspace.path : thread.cwd + return resolveWorkspaceCwd(localPath) +} + +const LOCAL_DELEGATED_TRANSPORTS = new Set>([ + 'codex-cli', 'claude-cli', 'opencode', 'kilo', 'pi-cli', 'cursor-cli', 'gemini-cli', +]) + +export function assertSshThreadTransportSupported(workspace: WorkspaceLocation | null, provider: Provider | null | undefined): void { + if (workspace?.kind === 'ssh' && provider?.transport && LOCAL_DELEGATED_TRANSPORTS.has(provider.transport)) { + throw new Error(`${provider.name || provider.transport} runs on this Mac and cannot safely use an SSH workspace. Choose an HTTP/model transport with SSH-backed tools, or run the delegated engine on the remote Orchestrator.`) + } +} + +export function assertSshToolContextConnected(workspace: WorkspaceLocation | null, toolContext: { backend?: unknown } | null | undefined): void { + if (workspace?.kind === 'ssh' && !toolContext?.backend) { + throw new Error('The SSH workspace disconnected during startup. Reconnect it before running the agent.') + } +} + +export function assertIncognitoThreadTransportSupported(thread: Pick, provider?: Pick): void { + if (thread.incognito && (thread.engine === 'omp' || provider?.transport && provider.transport !== 'chat-completions')) { + throw new Error('Incognito requires a TensorFold API chat. This agent runtime keeps its own session history; choose an API model or start an ordinary saved task.') + } +} diff --git a/app/electron/main/host/thread-run-settlement.ts b/app/electron/main/host/thread-run-settlement.ts new file mode 100644 index 00000000000..de9d8f8bc09 --- /dev/null +++ b/app/electron/main/host/thread-run-settlement.ts @@ -0,0 +1,221 @@ +import { canContributeThreadMemory } from '../../../shared/thread-memory-policy' +import { randomUUID } from 'node:crypto' +import { compactThreadJournal } from '../../agent/thread-journal' +import { assertProviderEndpointResolved } from '../../agent/security' +import { buildAgentRunReceipt, buildEventReceipt } from '../../agent/run-contract' +import type { Project, Provider, Thread } from '../../agent/types' +import { store } from '../state' +import { auditModelRetry, auditModelRoute, modelRouteAccountLabel, modelRouteAutoFailoverEnabled, modelRouteFailoverText, modelRouteResetPolicy, modelRouter, rememberProviderModels, runtimeProviderWithFreshModels } from './provider-runtime' + +import type { ThreadRoute, ThreadRouteContext } from './thread-run-execution' +import { botRunReasoningEffort } from '../../../shared/bot-reasoning' + +interface ThreadSettlementContext extends ThreadRouteContext { + initialRoute: ThreadRoute + baseProvider: Provider + project: Project | null + threadRouteRole: 'chat' | 'task' + runTimelineStart: number + runLease: { release(): void } + releaseBotVmRun(): void + runWithRoute(route: ThreadRoute, model?: string): Promise +} + +export function settleThreadExecution(pending: Promise, input: ThreadSettlementContext): void { + const { deps, support, thread, controller, runId, runTimelineStart, workspace, runContract, memoryPolicy, memoryRevision, localHelpersOnly, payload, jobHandle, review, runLease, releaseBotVmRun, baseProvider, project, threadRouteRole, runWithRoute, emit } = input + let activeRoute = input.initialRoute + let { provider, providerAccountId } = activeRoute + const { aborters, sshManager, emitToRenderer, persistThreads, patchJob, settleThreadRunJob, effectiveContextLimit } = deps + const { addThreadNotice, timelineErrorSince, markRouteErrorRecovered, markUndrainedCues, injectThreadRouteHandoff, availableModelsFromProviderError, compactThreadJournalTail, reviewViewedSkills, proposePostRunMemory } = support + void pending + .catch(async (err) => { + const liveModels = availableModelsFromProviderError(err) + const fallbackModel = liveModels.find((candidate) => candidate !== activeRoute.model) + if (fallbackModel && thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && !thread.bot && !controller.signal.aborted) { + const rejectedModel = activeRoute.model + markRouteErrorRecovered(thread, err, runId, `Model "${rejectedModel}" was rejected by ${baseProvider.name}; retrying with "${fallbackModel}".`) + rememberProviderModels(baseProvider.id, activeRoute.providerAccountId, liveModels) + activeRoute = { ...activeRoute, model: fallbackModel } + thread.model = fallbackModel + thread.updatedAt = Date.now() + persistThreads() + emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { model: fallbackModel } }) + const notice = { id: randomUUID(), kind: 'notice' as const, text: `Model "${rejectedModel}" was rejected by ${baseProvider.name}. Retrying with "${fallbackModel}".`, createdAt: Date.now() } + thread.timeline.push(notice) + emitToRenderer({ runId, threadId: thread.id, type: 'item_add', item: notice }) + await auditModelRetry(thread, { + providerId: baseProvider.id, + providerAccountId: activeRoute.providerAccountId, + fromModel: rejectedModel, + toModel: fallbackModel, + source: 'provider_available_models', + reason: `Provider rejected model "${rejectedModel}" and returned live alternatives.`, + availableModels: liveModels, + }) + try { + await runWithRoute(activeRoute, fallbackModel) + } catch (retryErr) { + emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((retryErr as any)?.message ?? retryErr) }) + } + return + } + // The route-recovery setup below performs un-try-caught awaits (audit, provider refresh, + // and assertProviderEndpointResolved — which throws when a failover endpoint resolves to a + // private IP). Without this guard a throw here rejects the catch callback itself; the chain + // has no further .catch, so it becomes an unhandled rejection and the user sees the run + // silently die. Wrap it so any failure surfaces as the same user-facing error event the + // non-recovered path emits, then fall through to the shared .finally. + try { + const latestBaseProvider = store.settings.providers.find((p) => p.id === baseProvider.id) ?? baseProvider + const routed = modelRouter.routeAfterError({ + role: threadRouteRole, + provider: latestBaseProvider, + accountId: activeRoute.providerAccountId, + model: activeRoute.model, + error: err, + allowFailover: thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && !thread.bot && (modelRouteAutoFailoverEnabled(latestBaseProvider, activeRoute.providerAccountId) || thread.modelRoute?.resetPolicy === 'rotate_on_limit'), + localOnly: project?.localOnly === true, + contextLimit: effectiveContextLimit(latestBaseProvider, activeRoute.model, activeRoute.providerAccountId), + reasoningEffort: botRunReasoningEffort(thread, store.settings.reasoningEffort), + budget: thread.kind, + source: 'thread_recovery', + }) + if (routed.signal) { + for (const audit of routed.audit) await auditModelRoute(thread, audit, routed.signal) + } + if (thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && routed.signal && routed.route.selected && routed.route.selectedAccountId !== activeRoute.providerAccountId && !controller.signal.aborted) { + markRouteErrorRecovered(thread, err, runId, `Recovered provider limit on ${modelRouteAccountLabel(latestBaseProvider, activeRoute.providerAccountId)} for ${activeRoute.model}; retrying on ${modelRouteAccountLabel(latestBaseProvider, routed.route.selectedAccountId)}.`) + const exhaustedAccountId = activeRoute.providerAccountId + providerAccountId = routed.route.selectedAccountId + provider = await runtimeProviderWithFreshModels(latestBaseProvider, providerAccountId) + await assertProviderEndpointResolved(provider) + activeRoute = { provider, providerAccountId, model: activeRoute.model } + thread.providerId = latestBaseProvider.id + thread.providerAccountId = providerAccountId + thread.model = activeRoute.model + thread.modelRoute = { + preferredProviderAccountId: exhaustedAccountId, + failoverProviderAccountId: providerAccountId, + resetPolicy: modelRouteResetPolicy(latestBaseProvider, exhaustedAccountId), + failedOverAt: Date.now(), + resetAt: routed.signal.resetAt, + reason: routed.route.audit.reason, + } + thread.updatedAt = Date.now() + persistThreads() + emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { providerId: thread.providerId, providerAccountId, model: activeRoute.model, modelRoute: thread.modelRoute } }) + addThreadNotice(thread, runId, modelRouteFailoverText(latestBaseProvider, routed.route.audit, routed.signal)) + injectThreadRouteHandoff(thread, `Thread "${thread.title}" failed over after ${routed.signal.kind.replace(/_/g, ' ')}.`) + try { + await runWithRoute(activeRoute) + } catch (retryErr) { + emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((retryErr as any)?.message ?? retryErr) }) + } + return + } + emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String(err?.message ?? err) }) + } catch (recoveryErr) { + // Recovery setup itself failed — surface the original error plus the recovery failure. + emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((recoveryErr as any)?.message ?? recoveryErr) }) + } + }) + .finally(() => { + let job = jobHandle.get() + markUndrainedCues(thread, controller.signal.aborted ? 'canceled' : 'run ended') + const failed = !!timelineErrorSince(thread, runTimelineStart) + const remoteTransport = workspace?.kind === 'ssh' && workspace.hostId && sshManager.status ? sshManager.status(workspace.hostId) : null + const transportUnverifiable = failed && !!remoteTransport && (remoteTransport.phase === 'disconnected' || remoteTransport.phase === 'error') + if (transportUnverifiable && workspace?.kind === 'ssh') { + const reason = remoteTransport?.lastError + ? `Remote transport lost: ${remoteTransport.lastError}` + : 'Remote transport lost; the process state is unverifiable.' + job = patchJob(job, { + executionVerification: 'unverifiable', + executionVerificationReason: reason, + executionVerifiedAt: Date.now(), + }) + } + jobHandle.set(job) + const recoveryPaused = thread.runRecovery?.runId === runId && ['paused', 'needs_review'].includes(thread.runRecovery.state) + const receipt = buildAgentRunReceipt({ thread, contract: runContract, timelineStart: runTimelineStart, aborted: controller.signal.aborted }) + const turnReceipt = buildEventReceipt({ + kind: 'turn_complete', + runId, + threadId: thread.id, + state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', + summary: receipt.summary, + evidenceRefs: [receipt.id], + }) + const jobReceipt = buildEventReceipt({ + kind: 'job_complete', + runId, + threadId: thread.id, + state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', + summary: `Thread job finished with ${receipt.verdict}.`, + evidenceRefs: [receipt.id], + }) + const savedReceipt = buildEventReceipt({ + kind: 'run_receipt_saved', + runId, + threadId: thread.id, + state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', + summary: 'Run receipt saved at run end.', + evidenceRefs: [receipt.id], + }) + receipt.eventReceipts.push(turnReceipt, jobReceipt, savedReceipt) + emit({ runId, threadId: thread.id, type: 'thread_update', patch: { activeRunContract: null, lastRunReceipt: receipt } }) + emit({ + runId, + threadId: thread.id, + type: 'item_add', + item: { + id: randomUUID(), + kind: 'notice', + title: 'Run receipt', + text: `Run receipt: ${receipt.verdict}. ${receipt.summary}`, + state: receipt.needsReview ? 'awaiting' : 'ok', + runReceipt: receipt, + eventReceipt: savedReceipt, + createdAt: Date.now(), + }, + }) + thread.status = failed ? 'error' : 'idle' + thread.updatedAt = Date.now() + // Only retire our own controller — never clobber a controller a later run installed. + if (aborters.get(thread.id) === controller) aborters.delete(thread.id) + runLease.release() + releaseBotVmRun() + settleThreadRunJob( + job, + thread, + controller.signal.aborted || transportUnverifiable || recoveryPaused ? 'paused' : failed ? 'failed' : 'completed', + transportUnverifiable + ? 'Remote transport disconnected; execution is unverifiable and must be reconciled after reconnecting.' + : recoveryPaused ? thread.runRecovery?.message : failed ? 'Thread agent run ended with an error.' : undefined, + ) + persistThreads() + // Bound the per-thread NDJSON journal: high-frequency item_delta chunks make it grow + // without limit since compactThreadJournal was never called in production. At run-end the + // events are already folded into the persisted thread snapshot, so keep only a recent tail + // for crash replay. Fire-and-forget; failures must not affect run settlement. + if (!thread.incognito) void compactThreadJournalTail(thread.id) + + // Skill self-improvement (opt-in): on a successful run that consulted a skill, let an + // aux model review those skills and FILE improvement suggestions (consent-first; never + // auto-applied). Fully fire-and-forget — it must never disturb the settled run. + if (!localHelpersOnly && !thread.phoneLocalOnly && !thread.googleLocalOnly && canContributeThreadMemory(thread, memoryPolicy, memoryRevision, controller.signal) && store.settings.skillSelfImprovement && !failed && !recoveryPaused && !controller.signal.aborted && review.viewedSkillNames.size && review.provider) { + void reviewViewedSkills({ provider: review.provider, model: review.model, thread, userText: payload.userText, viewed: [...review.viewedSkillNames], signal: controller.signal, memoryPolicy, memoryRevision }) + } + if (!failed && !recoveryPaused && !controller.signal.aborted) { + try { proposePostRunMemory(thread, memoryPolicy, memoryRevision, controller.signal) } catch { /* best effort — never disturb the settled run */ } + } + }) + // Backstop: every awaited path inside .catch/.finally is itself guarded, but attach a + // terminal handler so no recovery/journal failure can ever escape as an unhandled rejection. + .catch(() => { + if (aborters.get(thread.id) === controller) aborters.delete(thread.id) + runLease.release() + releaseBotVmRun() + }) + +} diff --git a/app/electron/main/host/thread-run-start.ts b/app/electron/main/host/thread-run-start.ts new file mode 100644 index 00000000000..93623e45218 --- /dev/null +++ b/app/electron/main/host/thread-run-start.ts @@ -0,0 +1,448 @@ +import { resolveMessageQuotes } from '../../agent/conversation-quotation' +import { assertRecoveryAllowsNewRun } from '../../agent/run-outcome-review' +import { apiUserMessageRef } from '../../agent/message-edit' +import { assertThreadMemoryTransport, captureThreadMemoryPolicy, threadMemoryPolicyRevision } from '../../../shared/thread-memory-policy' +import { assertGoogleContextTransport } from '../../../shared/google-workspace-privacy' +import { saveThreadMemoryPolicy } from '../../store' +import { randomUUID } from 'node:crypto' +import { restartResumeApprovalMode, claimJobLease } from '../../agent/jobs' +import { vontraPath } from '../../store' +import { buildUserContent } from '../../agent/content' +import { normalizeAttachments } from '../../agent/attachment-policy' +import { appendThreadEvent } from '../../agent/thread-journal' +import { resolveProviderModel, surfaceModelOverride } from '../../agent/provider-accounts' +import { assertLocalEndpointAvailable } from '../../agent/local-endpoint' +import { routeSpendStatus } from '../../agent/model-router' +import { assertProviderEndpointResolved } from '../../agent/security' +import { ensureAgentEventTrace } from '../../agent/trace' +import { buildAgentRunContract, buildEventReceipt } from '../../agent/run-contract' +import type { AgentEvent, Job, Provider, StartRunPayload, Thread } from '../../agent/types' +import { threadTurnNumber } from './checkpoint-runtime' +import { store } from '../state' +import { auditEvent, requireSecurityRole } from './audit' +import { auditModelRetry, auditModelRoute, modelRouteAccountLabel, modelRouteAutoFailoverEnabled, modelRouteFailoverText, modelRouteResetPolicy, modelRouter, runtimeProviderWithFreshModels, selectedProviderAccountId } from './provider-runtime' +import { canonicalLocalWorkspaceKey, lexicalLocalWorkspaceKey, sshWorkspaceKey } from './workspace-mutation-guard' +import { botRunApprovalMode } from '../../../shared/bot-policy' +import { botUsesGuardedExecution, isRestrictedBot } from '../../../shared/bot-tool-policy' +import { getBotVmHost } from './bot-vm-host' +import { assertBotLifecycleIdle, reserveBotVmRun } from './bot-run-boundary' +import { engineService } from './engine-runtime' +import { isEngineProvider } from '../../agent/engine/provider' + +import type { ThreadMemoryPolicy } from '../../agent/types' +import type { ThreadRuntime, ThreadRuntimeDeps, ThreadRunAdmission, JobHandle } from './thread-runtime' +import { encodeJournalEvent, journalKey } from './thread-journal-crypto' +import { recordPreTurnCheckpoint, resolveThreadRunCwd, assertSshThreadTransportSupported, assertIncognitoThreadTransportSupported } from './thread-run-policy' +import { createThreadRouteRunner, type ThreadRouteContext, type ThreadRunReview } from './thread-run-execution' +import { settleThreadExecution } from './thread-run-settlement' +import { botRunReasoningEffort } from '../../../shared/bot-reasoning' + +export interface ThreadRunSupport extends Pick { + availableModelsFromProviderError(error: unknown): string[] + compactThreadJournalTail(threadId: string): Promise + reviewViewedSkills(input: { provider: Provider; model: string; thread: Thread; userText: string; viewed: string[]; signal: AbortSignal; memoryPolicy: ThreadMemoryPolicy; memoryRevision: number }): Promise + proposePostRunMemory(thread: Thread, policy: ThreadMemoryPolicy, revision: number, signal: AbortSignal): void + maybeAutoTitle(thread: Thread, provider: Provider, model: string, text: string): void +} + +export function createThreadRunStarter(deps: ThreadRuntimeDeps, support: ThreadRunSupport): ThreadRuntime['startThreadRun'] { + const { aborters, jobLeaseOwner, sshManager, emitToRenderer, persistThreads, claimJob, patchJob, replaceJobResult, effectiveContextLimit } = deps + const { addThreadNotice, applyEventToThread, maybeAutoTitle } = support + + async function startThreadRun(payload: StartRunPayload, existingJob?: Job, admission?: ThreadRunAdmission): Promise<{ runId: string }> { + requireSecurityRole('operator', 'start agent runs') + admission?.assertAllowed() + if (Object.prototype.hasOwnProperty.call(payload, 'memoryPolicy')) throw new Error('Memory choices must be saved before starting a run.') + const thread = store.threads.find((t) => t.id === payload.threadId) + if (!thread) throw new Error('Thread not found') + if (thread.archivedAt) throw new Error('Restore this archived thread before starting it.') + const quotes = resolveMessageQuotes(thread, payload.quotes) + if (quotes.length && (payload.sourceThreadKey || thread.engine === 'omp')) throw new Error('Quoted replies need a local TensorFold chat API conversation.') + const runApprovalMode = botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, payload.approvalMode ?? restartResumeApprovalMode(existingJob?.resumeAfterRestart, store.settings.approvalMode)) + const botVm = thread.bot?.executionTarget === 'vm' + const restrictedBot = isRestrictedBot(thread.bot) + const localHelpersOnly = botUsesGuardedExecution(thread.bot) || thread.phoneLocalOnly === true || thread.googleLocalOnly === true + const assertBotResearchOff = (provider: Provider | undefined) => { + const engine = engineService() + // Also cover custom API aliases of the built-in server, including startup races. + if (engine?.hasExternalResearchEnabled() || isEngineProvider(provider) && !engine) throw new Error('Turn off Cortheon in AI settings before using an isolated or restricted bot; hidden research cannot enforce its execution boundary.') + } + const vmHost = botVm ? getBotVmHost() : null + if (thread.bot) { + assertBotLifecycleIdle(thread.bot.presetId) + if (thread.engine && thread.engine !== 'native') throw new Error('Bot chats require TensorFold permission checks.') + if (thread.providerId !== thread.bot.providerId || (thread.providerAccountId ?? null) !== thread.bot.providerAccountId || thread.model !== thread.bot.model) throw new Error('The model differs from the captured bot configuration; start a new bot chat.') + if (thread.workspace || thread.projectId || (botVm ? thread.cwd !== '/workspace' : !!thread.cwd)) throw new Error('The bot execution location has changed; start a new bot chat.') + if (botVm && !vmHost) throw new Error('The bot VM service is unavailable; the run will not use this Mac instead.') + } + // Guard against a second concurrent run for the same thread: it would overwrite the shared + // aborters[threadId] entry, so the first run's finally cleanup would delete the live run's + // controller (breaking cancel + cue queueing) and both runs would interleave apiMessages. + // Checked here (before any thread mutation) so a rejected start leaves state untouched. + if (aborters.has(thread.id)) throw new Error('Thread already running') + assertRecoveryAllowsNewRun(thread) + const project = thread.projectId ? store.projects.find((p) => p.id === thread.projectId) ?? null : null + if (thread.projectId && (!project || project.archivedAt)) throw new Error('Restore or choose an active project before starting this thread.') + const workspace = thread.workspace ?? project?.workspace ?? null + const workspaceBoundary = payload.workspaceBoundary ?? thread.workspaceBoundary ?? project?.workspaceBoundary + if (workspaceBoundary === 'home') await resolveThreadRunCwd(thread, workspace, workspaceBoundary) + const attachments = normalizeAttachments(payload.attachments) + const surfaceRoute = thread.providerId ? null : surfaceModelOverride(store.settings, thread.kind === 'chat' ? 'chat' : 'code') + const baseProvider = store.settings.providers.find((p) => p.id === (thread.providerId ?? surfaceRoute?.providerId ?? store.settings.activeProviderId)) + assertGoogleContextTransport(thread, baseProvider) + assertIncognitoThreadTransportSupported(thread, baseProvider) + assertThreadMemoryTransport(thread, baseProvider) + if (thread.incognito && existingJob && (existingJob.incognito !== true || existingJob.threadId !== thread.id || existingJob.currentThreadId !== thread.id)) throw new Error('An Incognito task cannot resume a saved or unrelated job; start a new private turn.') + assertSshThreadTransportSupported(workspace, baseProvider) + const initialWorkspaceKey = workspace?.kind === 'ssh' + ? sshWorkspaceKey(workspace.hostId, workspace.path) + : thread.kind === 'chat' || botVm ? null : lexicalLocalWorkspaceKey(workspace?.kind === 'local' ? workspace.path : thread.cwd) + // Admission and publishing aborters below are synchronous: a comparison cannot start + // between the local engine check and this run owning its host reservation. + admission?.assertAllowed() + if (isEngineProvider(baseProvider)) (deps.assertLocalEngineAdmission ?? (() => engineService()?.assertLocalWorkAdmission()))() + deps.workspaceMutationGuard.assertThreadStartAllowed(thread.id, initialWorkspaceKey) + const runLease = deps.workspaceMutationGuard.reserveStart({ threadId: thread.id, workspaceKeys: [initialWorkspaceKey] }) + let releaseBotVmRun = () => {} + try { if (botVm) releaseBotVmRun = reserveBotVmRun(thread.bot!.presetId, thread.id) } catch (error) { runLease.release(); throw error } + const controller = new AbortController() + aborters.set(thread.id, controller) + try { + admission?.onController(controller) + admission?.assertAllowed() + const memoryPolicy = captureThreadMemoryPolicy(thread) + if (botVm || restrictedBot) assertBotResearchOff(baseProvider) + if (botVm) { + await vmHost!.requireReady(thread.bot!.presetId) + if (controller.signal.aborted) throw new Error('Run cancelled before VM startup completed.') + assertBotResearchOff(baseProvider) + } + const canonicalWorkspaceKey = workspace?.kind === 'ssh' + ? sshWorkspaceKey(workspace.hostId, workspace.path) + : thread.kind === 'chat' || botVm ? null : await canonicalLocalWorkspaceKey(workspace?.kind === 'local' ? workspace.path : thread.cwd) + runLease.addWorkspaceKeys?.([canonicalWorkspaceKey]) + if (workspace?.kind === 'ssh' && workspace.hostId) { + try { + await sshManager.ensureConnected(workspace.hostId) + } catch (e) { + const message = `SSH connection failed: ${e instanceof Error ? e.message : String(e)}` + emitToRenderer({ runId: '', threadId: thread.id, type: 'error', message }) + throw new Error(message) + } + } + + // Per-surface defaults (VST-015): a thread that never had a provider stamped on it + // launches on its SURFACE's default (chat → assistant model, task → coding model) before + // falling back to the globally-active route. An explicitly-configured thread is untouched. + if (!baseProvider) throw new Error('No provider configured. Open Settings to add one.') + const storedProviderAccountId = Object.prototype.hasOwnProperty.call(thread, 'providerAccountId') + ? (thread.providerAccountId ?? null) + : surfaceRoute && surfaceRoute.providerId === baseProvider.id && surfaceRoute.providerAccountId + ? surfaceRoute.providerAccountId + : selectedProviderAccountId(baseProvider, undefined) + let requestedProviderAccountId = storedProviderAccountId + const routeMemory = thread.modelRoute ?? null + const resetReturn = routeMemory?.resetPolicy === 'return_after_reset' && + routeMemory.resetAt != null && + routeMemory.resetAt <= Date.now() && + routeMemory.failoverProviderAccountId === storedProviderAccountId && + routeMemory.preferredProviderAccountId !== storedProviderAccountId + ? { from: routeMemory.failoverProviderAccountId, to: routeMemory.preferredProviderAccountId, resetAt: routeMemory.resetAt } + : null + if (resetReturn) requestedProviderAccountId = resetReturn.to + const requestedModel = thread.model ?? (surfaceRoute && surfaceRoute.providerId === baseProvider.id ? surfaceRoute.model : null) ?? store.settings.activeModel + const threadRouteRole = thread.kind === 'chat' ? 'chat' : 'task' + if (project?.localOnly && baseProvider.kind !== 'local') { + const blockedModel = resolveProviderModel(baseProvider, requestedProviderAccountId, requestedModel) ?? requestedModel ?? store.settings.activeModel ?? baseProvider.models[0] ?? 'unknown' + const blockedRoute = modelRouter.select({ + role: threadRouteRole, + provider: baseProvider, + model: blockedModel, + requestedAccountId: requestedProviderAccountId, + allowFailover: modelRouteAutoFailoverEnabled(baseProvider, requestedProviderAccountId), + localOnly: true, + contextLimit: effectiveContextLimit(baseProvider, blockedModel, requestedProviderAccountId), + reasoningEffort: botRunReasoningEffort(thread, store.settings.reasoningEffort), + budget: thread.kind, + source: 'thread_local_only_guard', + }) + await auditModelRoute(thread, blockedRoute.audit) + throw new Error(blockedRoute.audit.reason) + } + const requestedProvider = await runtimeProviderWithFreshModels(baseProvider, requestedProviderAccountId) + const routeBaseProvider = store.settings.providers.find((p) => p.id === baseProvider.id) ?? baseProvider + const model = resolveProviderModel(requestedProvider, null, requestedModel) + if (!model) throw new Error('No model selected.') + if (thread.bot && model !== thread.bot.model) throw new Error('The saved bot model is unavailable; edit the bot and start a new chat.') + const initialRoute = modelRouter.select({ + role: threadRouteRole, + provider: routeBaseProvider, + model, + requestedAccountId: requestedProviderAccountId, + allowFailover: !thread.bot && modelRouteAutoFailoverEnabled(routeBaseProvider, requestedProviderAccountId), + localOnly: project?.localOnly === true, + contextLimit: effectiveContextLimit(routeBaseProvider, model, requestedProviderAccountId), + reasoningEffort: botRunReasoningEffort(thread, store.settings.reasoningEffort), + budget: thread.kind, + source: 'thread_initial_route', + }) + if (!initialRoute.selected) { + await auditModelRoute(thread, initialRoute.audit) + throw new Error(initialRoute.audit.reason) + } + let providerAccountId = initialRoute.selectedAccountId + let provider = providerAccountId === requestedProviderAccountId + ? requestedProvider + : await runtimeProviderWithFreshModels(routeBaseProvider, providerAccountId) + await assertProviderEndpointResolved(provider) + // Local endpoint availability (VST-015): if a local provider's server is not listening, + // refuse now with a named error instead of failing mid-run with a generic fetch error. + await assertLocalEndpointAvailable(provider) + if (thread.providerAccountId !== providerAccountId || thread.model !== model) { + const staleModel = requestedModel && requestedModel !== model ? requestedModel : null + thread.providerId = baseProvider.id + thread.providerAccountId = providerAccountId + if (resetReturn && providerAccountId === resetReturn.to) thread.modelRoute = null + thread.model = model + thread.updatedAt = Date.now() + persistThreads() + emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { providerId: thread.providerId, providerAccountId, model, modelRoute: thread.modelRoute } }) + if (staleModel) { + const notice = { id: randomUUID(), kind: 'notice' as const, text: `Model "${staleModel}" is unavailable. Switched to "${model}".`, createdAt: Date.now() } + thread.timeline.push(notice) + emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: notice }) + await auditModelRetry(thread, { + providerId: routeBaseProvider.id, + providerAccountId, + fromModel: staleModel, + toModel: model, + source: 'startup_model_resolution', + reason: `Saved model "${staleModel}" was unavailable for the selected route.`, + availableModels: provider.models, + }) + } + } + if (resetReturn && providerAccountId === resetReturn.to) { + addThreadNotice(thread, '', `Model router returned to ${modelRouteAccountLabel(routeBaseProvider, providerAccountId)} after the reset window.`) + await auditEvent('model_router.return_after_reset', { + threadId: thread.id, + providerId: routeBaseProvider.id, + model, + previousAccountId: resetReturn.from, + selectedAccountId: providerAccountId, + resetAt: resetReturn.resetAt, + }) + } + if (initialRoute.audit.action === 'failover') { + const resetAt = initialRoute.candidates.find((candidate) => candidate.accountId === initialRoute.requestedAccountId)?.exhaustedUntil ?? null + thread.modelRoute = { + preferredProviderAccountId: initialRoute.requestedAccountId, + failoverProviderAccountId: initialRoute.selectedAccountId, + resetPolicy: modelRouteResetPolicy(routeBaseProvider, initialRoute.requestedAccountId), + failedOverAt: Date.now(), + resetAt, + reason: initialRoute.audit.reason, + } + thread.updatedAt = Date.now() + persistThreads() + emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { modelRoute: thread.modelRoute } }) + addThreadNotice(thread, '', modelRouteFailoverText(routeBaseProvider, initialRoute.audit)) + await auditModelRoute(thread, initialRoute.audit) + } + if (thread.kind !== 'chat' && !botVm) thread.cwd = await resolveThreadRunCwd(thread, workspace, workspaceBoundary) + + if (controller.signal.aborted) throw new Error('Run cancelled before startup completed.') + const acceptedMemoryThread = await saveThreadMemoryPolicy(() => store.threads, thread.id, memoryPolicy, threadMemoryPolicyRevision(thread)) + const memoryRevision = threadMemoryPolicyRevision(acceptedMemoryThread) + // Publish the durable startup CAS pair before a possible Stop returns control to the UI. + emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { memoryPolicy: { ...captureThreadMemoryPolicy(acceptedMemoryThread) }, memoryPolicyRevision: memoryRevision } }) + if (controller.signal.aborted) throw new Error('Run cancelled after memory choices were accepted.') + assertGoogleContextTransport(thread, provider) + admission?.assertAllowed() + if (quotes.length && provider.transport && provider.transport !== 'chat-completions') throw new Error('Quoted replies need a model using the TensorFold chat API.') + resolveMessageQuotes(thread, quotes) + const userContent = buildUserContent(payload.userText, attachments, quotes) + const userItem = { id: randomUUID(), kind: 'user' as const, apiMessageRef: apiUserMessageRef(thread.apiMessages, userContent, thread.compactions?.length ?? 0), memorySource: payload.sourceThreadKey ? 'external' as const : 'user' as const, text: payload.userText, attachments, ...(quotes.length ? { quotedMessages: quotes } : {}), createdAt: Date.now() } + thread.timeline.push(userItem) + thread.apiMessages.push({ role: 'user', content: userContent }) + thread.status = 'running' + thread.updatedAt = Date.now() + emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: userItem }) + + const runId = randomUUID() + const runMaxWallMs = 30 * 60_000 + const runContract = buildAgentRunContract({ + thread, + runId, + objective: payload.userText, + provider, + providerAccountId, + model, + approvalMode: runApprovalMode, + maxWallMs: runMaxWallMs, + }) + let job: Job | null = existingJob + ? replaceJobResult(claimJobLease(store.jobs, existingJob.id, jobLeaseOwner)) + : claimJob({ + kind: 'thread', + incognito: thread.incognito === true, + owner: thread.id, + projectId: thread.projectId ?? null, + threadId: thread.id, + currentThreadId: thread.id, + resumeAfterRestart: 'ask', + metadata: { title: thread.title, kind: thread.kind, model }, + }) + job = patchJob(job, { + currentRunId: runId, + currentThreadId: thread.id, + blockedReason: null, + executionHostId: workspace?.kind === 'ssh' ? workspace.hostId : null, + executionVerification: workspace?.kind === 'ssh' ? 'live' : null, + executionVerificationReason: workspace?.kind === 'ssh' ? 'Remote workspace connected for this run.' : null, + executionVerifiedAt: workspace?.kind === 'ssh' ? Date.now() : null, + metadata: { + currentRunId: runId, + currentThreadId: thread.id, + currentThreadTitle: thread.title, + currentThreadKind: thread.kind, + providerId: baseProvider.id, + providerAccountId, + model, + }, + }) + const jobHandle: JobHandle = { + get: () => job, + set: (next) => { job = next }, + } + + const emit = (e: AgentEvent) => { + const traced = ensureAgentEventTrace(e, 'agent.run') + applyEventToThread(thread, traced) + // Append to the crash-safe per-thread NDJSON journal: bounds data loss to the last unflushed + // event (not the last whole-thread snapshot) and gives an ordered, replayable run record. + // Encrypt the event with the app key so the on-disk journal matches threads.json's + // at-rest encryption posture (the journal holds the full plaintext transcript otherwise). + const journalEvent = thread.incognito ? null : encodeJournalEvent(traced, journalKey()) + if (journalEvent !== null) void appendThreadEvent(vontraPath('thread-journals'), thread.id, journalEvent) + emitToRenderer(traced) + } + + // Everything after the user turn belongs to this run's durable contract/receipt window. + const runTimelineStart = thread.timeline.length + emit({ runId, threadId: thread.id, type: 'thread_update', patch: { activeRunContract: runContract } }) + emit({ + runId, + threadId: thread.id, + type: 'item_add', + item: { + id: randomUUID(), + kind: 'notice', + title: 'Run contract', + text: `Run contract saved: ${runContract.surface} on ${runContract.targetKind} with ${runContract.model || 'no model'}.`, + state: 'ok', + runContract, + eventReceipt: buildEventReceipt({ + kind: 'run_contract_saved', + runId, + threadId: thread.id, + state: 'ok', + summary: 'Run contract saved before model execution.', + evidenceRefs: [runContract.id], + }), + createdAt: Date.now(), + }, + }) + + // Spend telemetry (VST-015): a near-cap budget WARNS into the timeline before the first + // model call. The hard stop needs no gate here — the initial modelRouter.select() above + // already refuses over-budget routes (applySpendControls → no_route → the throw at the + // route check), which the renderer surfaces as a visible run-refused error notice. + const initialSpend = routeSpendStatus(routeBaseProvider, providerAccountId) + if (initialSpend.warning) { + emit({ runId, threadId: thread.id, type: 'item_add', item: { id: randomUUID(), kind: 'notice', title: 'Budget', text: initialSpend.warning, state: 'ok', createdAt: Date.now() } }) + } + + if (!localHelpersOnly && !thread.googleLocalOnly && (thread.title === 'New task' || thread.title === 'New chat')) maybeAutoTitle(thread, provider, model, payload.userText) + + const review: ThreadRunReview = { viewedSkillNames: new Set(), provider: null, model: '' } + const routeContext: ThreadRouteContext = { + deps, + support, + thread, + controller, + admission, + botVm, + restrictedBot, + vmHost, + workspace, + memoryPolicy, + memoryRevision, + runId, + runApprovalMode, + runContract, + runMaxWallMs, + localHelpersOnly, + payload, + jobHandle, + review, + assertBotResearchOff, + emit, + } + const runWithRoute = createThreadRouteRunner(routeContext) + + let activeRoute = { provider, providerAccountId, model } + // Scope the run's success/failure to items THIS run appends — a leftover error item from a + // previous run must not mark a later successful run as failed (which stalls the PR loop). + + // Skill self-improvement bookkeeping: which skills the agent consulted this run, and the + // provider/model it ran on (so the post-run review reuses the same backend). Populated in + // auditToolCall + runWithRoute; consumed in the .finally review pass. + + // Repo-authored skills rescan (VST-010): awaited so this run's context reflects the + // trust state of the content on disk RIGHT NOW (a just-edited trusted skill drops out + // until re-reviewed). Missing dirs and scan errors degrade to "no project skills". + if (deps.refreshProjectSkills && thread.projectId) { + const project = store.projects.find((p) => p.id === thread.projectId) + if (project) await deps.refreshProjectSkills({ id: project.id, cwd: project.cwd, workspace }).catch(() => {}) + } + + // Finish the pre-turn file snapshot before the model can invoke a write tool. + // Capture remains best-effort, but fire-and-forget here would race a fast local + // model and could accidentally snapshot post-edit state. The returned SHA ties + // the conversation record to a file ref only when capture really succeeded. + const checkpointTurn = threadTurnNumber(thread.timeline) + await recordPreTurnCheckpoint({ + threadId: thread.id, + incognito: thread.incognito, + turn: checkpointTurn, + target: { cwd: thread.cwd, workspace, kind: thread.kind }, + conversation: { + apiMessages: thread.apiMessages ?? [], + timeline: thread.timeline ?? [], + goal: thread.goal, + goalStatus: (thread as { goalStatus?: string }).goalStatus, + plan: (thread as { plan?: unknown[] }).plan, + status: thread.status, + }, + }, deps) + + settleThreadExecution(runWithRoute(activeRoute), { + ...routeContext, initialRoute: activeRoute, baseProvider, project, threadRouteRole, + runTimelineStart, runLease, releaseBotVmRun, runWithRoute, + }) + + return { runId } + } catch (err) { + if (aborters.get(thread.id) === controller) aborters.delete(thread.id) + runLease.release() + releaseBotVmRun() + throw err + } + } + + return startThreadRun +} diff --git a/app/electron/main/host/thread-runtime.ts b/app/electron/main/host/thread-runtime.ts index fa0ba3c018e..4802acb08ff 100644 --- a/app/electron/main/host/thread-runtime.ts +++ b/app/electron/main/host/thread-runtime.ts @@ -1,126 +1,34 @@ -import { resolveMessageQuotes } from '../../agent/conversation-quotation' -import { selectedResponseLocale } from '../../agent/response-language' -import { RunRecoveryTracker } from '../../agent/run-recovery/tracker' -import { assertRecoveryAllowsNewRun } from '../../agent/run-outcome-review' -import { apiUserMessageRef } from '../../agent/message-edit' -import { assertThreadMemoryTransport, captureThreadMemoryPolicy, canContributeThreadMemory, threadMemoryPolicyRevision } from '../../../shared/thread-memory-policy' +import { createThreadRunStarter } from './thread-run-start' +import { canContributeThreadMemory } from '../../../shared/thread-memory-policy' import { assertGoogleContextTransport } from '../../../shared/google-workspace-privacy' -import { saveThreadMemoryPolicy } from '../../store' import { randomUUID } from 'node:crypto' -import { restartResumeApprovalMode, claimJobLease } from '../../agent/jobs' import type { JobPatch } from '../../agent/jobs' -import { runAgent } from '../../agent/loop' -import { runOmpThread } from '../../agent/omp-engine' -import { assertOmpEngineAllowed } from '../../agent/planning-guard' -import { executeTool, isReadOnlyTool } from '../../agent/tools' -import { createSubAgentFromLaunch, parentForThread, updateSubAgent } from '../../agent/subagents' -import { saveSubAgents, vontraPath } from '../../store' -import { selectChannelPrompt } from '../../agent/channel-prompt' +import { vontraPath } from '../../store' import { buildUserContent, contentText } from '../../agent/content' import { normalizeAttachments } from '../../agent/attachment-policy' -import { appendThreadEvent, compactThreadJournal, readThreadJournal } from '../../agent/thread-journal' +import { compactThreadJournal, readThreadJournal } from '../../agent/thread-journal' import { quickComplete, streamChat } from '../../agent/openai' import { createThreadTitleGenerator } from './thread-title' import { harvestPostRunMemoryCandidates } from '../../agent/memory-harvest' import { reviewSkillsAfterRun } from '../../agent/skill-self-improvement' import { addSuggestion } from '../../agent/suggestions' -import { resolveProviderModel, surfaceModelOverride } from '../../agent/provider-accounts' -import { assertLocalEndpointAvailable } from '../../agent/local-endpoint' -import { routeSpendStatus } from '../../agent/model-router' -import { ensureTensorFoldStudioStylePrompt } from '../../agent/prompt-style' -import { resolvePersona, personaSystemBlock } from '../../agent/persona' import { createProjectMemoryCandidate, scopeProjectMemoryEntries } from '../../agent/project-memory' import { projectMemoryAutoCandidateTurn, projectMemoryAutoMessages } from './project-memory-auto-policy' import { persistProjectMemoryCandidates, persistSuggestions } from './persistence' -import { assertProviderEndpointResolved, auditPreview } from '../../agent/security' -import { ensureAgentEventTrace, ensureTimelineItemTrace } from '../../agent/trace' -import { buildAgentRunContract, buildAgentRunReceipt, buildEventReceipt } from '../../agent/run-contract' +import { ensureTimelineItemTrace } from '../../agent/trace' +import { buildEventReceipt } from '../../agent/run-contract' import type { AgentCue, AgentEvent, ApiMessage, CueRunPayload, CueRunResult, Job, Project, Provider, Room, Seat, StartRunPayload, Thread, TimelineItem, WorkspaceLocation } from '../../agent/types' -import { threadTurnNumber } from './checkpoint-runtime' import { approvalPolicyScope, type ApprovalPolicyScope } from '../../agent/approval-policy' import { store } from '../state' -import { auditEvent, requireSecurityRole } from './audit' -import { - auditModelRetry, - auditModelRoute, - modelRouteAccountLabel, - modelRouteAutoFailoverEnabled, - modelRouteFailoverText, - modelRouteResetPolicy, - modelRouter, - rememberProviderModels, - routeHandoffPreview, - runtimeProviderWithFreshModels, - selectedProviderAccountId, -} from './provider-runtime' -import { resolveWorkspaceCwd } from './workspace' -import { resolvePairedWorkspace } from '../../agent/local-workspace-policy' -import { encryptWithKey, decryptWithKey, resolveLocalSecretKeySync } from '../../local-crypto' -import { canonicalLocalWorkspaceKey, lexicalLocalWorkspaceKey, sshWorkspaceKey, type WorkspaceMutationGuard } from './workspace-mutation-guard' -import { botInstructions, botRunApprovalMode } from '../../../shared/bot-policy' -import { botUsesGuardedExecution, isRestrictedBot } from '../../../shared/bot-tool-policy' -import { scopeBotToolContext } from '../../agent/bot-tool-scope' -import { createBotVmToolContext, getBotVmHost } from './bot-vm-host' -import { assertBotLifecycleIdle, reserveBotVmRun } from './bot-run-boundary' -import { engineService } from './engine-runtime' -import { isEngineProvider } from '../../agent/engine/provider' -import { getUserQuestionHost } from './user-question-host' -import { isExternalProvider } from '../../../shared/provider-trust' -import { INCOGNITO_PERSISTENT_TOOLS } from '../../agent/incognito' -import { PluginRuntime } from '../../agent/plugin-runtime' -import type { UserQuestionInput, UserQuestionRun } from '../../agent/types' +import { requireSecurityRole } from './audit' +import { routeHandoffPreview } from './provider-runtime' +import { type WorkspaceMutationGuard } from './workspace-mutation-guard' +import { botRunApprovalMode } from '../../../shared/bot-policy' +import { assertBotLifecycleIdle } from './bot-run-boundary' -// Per-thread NDJSON journals hold the FULL transcript (messages, tool args, tool output, -// diffs) — the most sensitive data in the app. threads.json is encrypted at rest via -// writeProtectedJson, so writing the journal as plaintext NDJSON defeats the same -// at-rest posture (local-crypto.ts: casual disk reads / accidental settings-dir sharing). -// We encrypt each journal event with the same app key, keeping the {seq, ts} envelope in -// the clear so compaction (which only reads seq) keeps working without a key. -const JOURNAL_ENC_PREFIX = 'enc:v1:' +export { encodeJournalEvent, decodeJournalEvent } from './thread-journal-crypto' -// Lazily resolve the same primary/fallback keys as store.ts. Failure disables the -// best-effort journal; it must never downgrade a full transcript to plaintext. -let cachedJournalKey: Buffer | null = null -function journalKey(): Buffer | null { - if (cachedJournalKey) return cachedJournalKey - try { - cachedJournalKey = resolveLocalSecretKeySync(vontraPath('.secretkey')).key - return cachedJournalKey - } catch { - return null - } -} - -// Wrap an AgentEvent for the journal: encrypt its JSON with the app key when available, -// emitting { e: 'enc:v1:' }. If crypto is unavailable, return null so -// the caller skips this optional journal rather than leaking the event verbatim. -export function encodeJournalEvent(event: unknown, key: Buffer | null): unknown | null { - if (!key) return null - try { - return { e: JOURNAL_ENC_PREFIX + encryptWithKey(JSON.stringify(event), key) } - } catch { - return null - } -} - -// Inverse of encodeJournalEvent: decrypt an encrypted journal envelope back to the -// original event, tolerating legacy/plaintext lines written before encryption existed. -export function decodeJournalEvent(stored: unknown, key: Buffer | null): unknown { - if (stored && typeof stored === 'object' && typeof (stored as { e?: unknown }).e === 'string') { - const payload = (stored as { e: string }).e - if (payload.startsWith(JOURNAL_ENC_PREFIX)) { - if (!key) return null // cannot decrypt without the key - try { - return JSON.parse(decryptWithKey(payload.slice(JOURNAL_ENC_PREFIX.length), key)) - } catch { - return null // wrong key / tampered / corrupt - } - } - } - return stored // legacy plaintext event written before journal encryption -} - -interface JobHandle { +export interface JobHandle { get(): Job | null set(job: Job | null): void } @@ -148,7 +56,7 @@ export interface ThreadRuntime { waitForThreadCue(threadId: string, timeoutMs: number, signal: AbortSignal): Promise } -interface ThreadRuntimeDeps { +export interface ThreadRuntimeDeps { aborters: Map workspaceMutationGuard: Pick assertLocalEngineAdmission?: () => void @@ -186,77 +94,14 @@ interface ThreadRuntimeDeps { observe?: (kind: 'api.request' | 'api.response', payload: Record) => void } -export async function recordPreTurnCheckpoint(input: { - threadId: string - incognito?: boolean - turn: number - target: { cwd?: string | null; workspace?: WorkspaceLocation | null; kind?: Thread['kind'] } - conversation: { apiMessages: unknown[]; timeline: unknown[]; goal?: string; goalStatus?: string; plan?: unknown[]; status?: string } -}, deps: Pick): Promise { - if (input.incognito) return - let fileSha: string | null = null - if (deps.captureCheckpoint && input.target.kind !== 'chat') { - try { - const captured = await deps.captureCheckpoint(input.threadId, input.turn, input.target) - if (captured.ok && captured.sha) fileSha = captured.sha - } catch { /* file checkpoints are best-effort; still retain the conversation snapshot */ } - } - try { deps.recordTurnCheckpoint?.(input.threadId, input.turn, input.conversation, fileSha) } catch { /* best effort */ } -} - -export async function resolveThreadRunCwd(thread: Pick, workspace: WorkspaceLocation | null, boundary = thread.workspaceBoundary): Promise { - if (thread.kind === 'chat') return thread.cwd - if (boundary === 'home') return resolvePairedWorkspace(thread.cwd, workspace) - if (workspace?.kind === 'ssh') { - const remotePath = String(workspace.path || '').trim() - if (!remotePath) throw new Error('Choose a remote workspace folder before running workspace tools.') - return remotePath - } - const localPath = workspace?.kind === 'local' && workspace.path ? workspace.path : thread.cwd - return resolveWorkspaceCwd(localPath) -} - -const LOCAL_DELEGATED_TRANSPORTS = new Set>([ - 'codex-cli', 'claude-cli', 'opencode', 'kilo', 'pi-cli', 'cursor-cli', 'gemini-cli', -]) - -export function assertSshThreadTransportSupported(workspace: WorkspaceLocation | null, provider: Provider | null | undefined): void { - if (workspace?.kind === 'ssh' && provider?.transport && LOCAL_DELEGATED_TRANSPORTS.has(provider.transport)) { - throw new Error(`${provider.name || provider.transport} runs on this Mac and cannot safely use an SSH workspace. Choose an HTTP/model transport with SSH-backed tools, or run the delegated engine on the remote Orchestrator.`) - } -} - -export function assertSshToolContextConnected(workspace: WorkspaceLocation | null, toolContext: { backend?: unknown } | null | undefined): void { - if (workspace?.kind === 'ssh' && !toolContext?.backend) { - throw new Error('The SSH workspace disconnected during startup. Reconnect it before running the agent.') - } -} - -export function assertIncognitoThreadTransportSupported(thread: Pick, provider?: Pick): void { - if (thread.incognito && (thread.engine === 'omp' || provider?.transport && provider.transport !== 'chat-completions')) { - throw new Error('Incognito requires a TensorFold API chat. This agent runtime keeps its own session history; choose an API model or start an ordinary saved task.') - } -} +export { recordPreTurnCheckpoint, resolveThreadRunCwd, assertSshThreadTransportSupported, assertSshToolContextConnected, assertIncognitoThreadTransportSupported } from './thread-run-policy' export function createThreadRuntime(deps: ThreadRuntimeDeps): ThreadRuntime { const { aborters, pendingApprovalMeta, - jobLeaseOwner, - threadJobHeartbeatMs, - sshManager, emitToRenderer, persistThreads, - fullToolContext, - approvalResolver, - isHighRiskTool, - claimJob, - patchJob, - replaceJobResult, - heartbeatJob, - settleThreadRunJob, - renderProjectMemoryBucket, - effectiveContextLimit, } = deps const cueQueues = new Map() const cueWaiters = new Map void>>() @@ -489,743 +334,6 @@ export function createThreadRuntime(deps: ThreadRuntimeDeps): ThreadRuntime { persistProjectMemoryCandidates() } - async function startThreadRun(payload: StartRunPayload, existingJob?: Job, admission?: ThreadRunAdmission): Promise<{ runId: string }> { - requireSecurityRole('operator', 'start agent runs') - admission?.assertAllowed() - if (Object.prototype.hasOwnProperty.call(payload, 'memoryPolicy')) throw new Error('Memory choices must be saved before starting a run.') - const thread = store.threads.find((t) => t.id === payload.threadId) - if (!thread) throw new Error('Thread not found') - if (thread.archivedAt) throw new Error('Restore this archived thread before starting it.') - const quotes = resolveMessageQuotes(thread, payload.quotes) - if (quotes.length && (payload.sourceThreadKey || thread.engine === 'omp')) throw new Error('Quoted replies need a local TensorFold chat API conversation.') - const runApprovalMode = botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, payload.approvalMode ?? restartResumeApprovalMode(existingJob?.resumeAfterRestart, store.settings.approvalMode)) - const botVm = thread.bot?.executionTarget === 'vm' - const restrictedBot = isRestrictedBot(thread.bot) - const localHelpersOnly = botUsesGuardedExecution(thread.bot) || thread.phoneLocalOnly === true || thread.googleLocalOnly === true - const assertBotResearchOff = (provider: Provider | undefined) => { - const engine = engineService() - // Also cover custom API aliases of the built-in server, including startup races. - if (engine?.hasExternalResearchEnabled() || isEngineProvider(provider) && !engine) throw new Error('Turn off Cortheon in AI settings before using an isolated or restricted bot; hidden research cannot enforce its execution boundary.') - } - const vmHost = botVm ? getBotVmHost() : null - if (thread.bot) { - assertBotLifecycleIdle(thread.bot.presetId) - if (thread.engine && thread.engine !== 'native') throw new Error('Bot chats require TensorFold permission checks.') - if (thread.providerId !== thread.bot.providerId || (thread.providerAccountId ?? null) !== thread.bot.providerAccountId || thread.model !== thread.bot.model) throw new Error('The model differs from the captured bot configuration; start a new bot chat.') - if (thread.workspace || thread.projectId || (botVm ? thread.cwd !== '/workspace' : !!thread.cwd)) throw new Error('The bot execution location has changed; start a new bot chat.') - if (botVm && !vmHost) throw new Error('The bot VM service is unavailable; the run will not use this Mac instead.') - } - // Guard against a second concurrent run for the same thread: it would overwrite the shared - // aborters[threadId] entry, so the first run's finally cleanup would delete the live run's - // controller (breaking cancel + cue queueing) and both runs would interleave apiMessages. - // Checked here (before any thread mutation) so a rejected start leaves state untouched. - if (aborters.has(thread.id)) throw new Error('Thread already running') - assertRecoveryAllowsNewRun(thread) - const project = thread.projectId ? store.projects.find((p) => p.id === thread.projectId) ?? null : null - if (thread.projectId && (!project || project.archivedAt)) throw new Error('Restore or choose an active project before starting this thread.') - const workspace = thread.workspace ?? project?.workspace ?? null - const workspaceBoundary = payload.workspaceBoundary ?? thread.workspaceBoundary ?? project?.workspaceBoundary - if (workspaceBoundary === 'home') await resolveThreadRunCwd(thread, workspace, workspaceBoundary) - const attachments = normalizeAttachments(payload.attachments) - const surfaceRoute = thread.providerId ? null : surfaceModelOverride(store.settings, thread.kind === 'chat' ? 'chat' : 'code') - const baseProvider = store.settings.providers.find((p) => p.id === (thread.providerId ?? surfaceRoute?.providerId ?? store.settings.activeProviderId)) - assertGoogleContextTransport(thread, baseProvider) - assertIncognitoThreadTransportSupported(thread, baseProvider) - assertThreadMemoryTransport(thread, baseProvider) - if (thread.incognito && existingJob && (existingJob.incognito !== true || existingJob.threadId !== thread.id || existingJob.currentThreadId !== thread.id)) throw new Error('An Incognito task cannot resume a saved or unrelated job; start a new private turn.') - assertSshThreadTransportSupported(workspace, baseProvider) - const initialWorkspaceKey = workspace?.kind === 'ssh' - ? sshWorkspaceKey(workspace.hostId, workspace.path) - : thread.kind === 'chat' || botVm ? null : lexicalLocalWorkspaceKey(workspace?.kind === 'local' ? workspace.path : thread.cwd) - // Admission and publishing aborters below are synchronous: a comparison cannot start - // between the local engine check and this run owning its host reservation. - admission?.assertAllowed() - if (isEngineProvider(baseProvider)) (deps.assertLocalEngineAdmission ?? (() => engineService()?.assertLocalWorkAdmission()))() - deps.workspaceMutationGuard.assertThreadStartAllowed(thread.id, initialWorkspaceKey) - const runLease = deps.workspaceMutationGuard.reserveStart({ threadId: thread.id, workspaceKeys: [initialWorkspaceKey] }) - let releaseBotVmRun = () => {} - try { if (botVm) releaseBotVmRun = reserveBotVmRun(thread.bot!.presetId, thread.id) } catch (error) { runLease.release(); throw error } - const controller = new AbortController() - aborters.set(thread.id, controller) - try { - admission?.onController(controller) - admission?.assertAllowed() - const memoryPolicy = captureThreadMemoryPolicy(thread) - if (botVm || restrictedBot) assertBotResearchOff(baseProvider) - if (botVm) { - await vmHost!.requireReady(thread.bot!.presetId) - if (controller.signal.aborted) throw new Error('Run cancelled before VM startup completed.') - assertBotResearchOff(baseProvider) - } - const canonicalWorkspaceKey = workspace?.kind === 'ssh' - ? sshWorkspaceKey(workspace.hostId, workspace.path) - : thread.kind === 'chat' || botVm ? null : await canonicalLocalWorkspaceKey(workspace?.kind === 'local' ? workspace.path : thread.cwd) - runLease.addWorkspaceKeys?.([canonicalWorkspaceKey]) - if (workspace?.kind === 'ssh' && workspace.hostId) { - try { - await sshManager.ensureConnected(workspace.hostId) - } catch (e) { - const message = `SSH connection failed: ${e instanceof Error ? e.message : String(e)}` - emitToRenderer({ runId: '', threadId: thread.id, type: 'error', message }) - throw new Error(message) - } - } - - // Per-surface defaults (VST-015): a thread that never had a provider stamped on it - // launches on its SURFACE's default (chat → assistant model, task → coding model) before - // falling back to the globally-active route. An explicitly-configured thread is untouched. - if (!baseProvider) throw new Error('No provider configured. Open Settings to add one.') - const storedProviderAccountId = Object.prototype.hasOwnProperty.call(thread, 'providerAccountId') - ? (thread.providerAccountId ?? null) - : surfaceRoute && surfaceRoute.providerId === baseProvider.id && surfaceRoute.providerAccountId - ? surfaceRoute.providerAccountId - : selectedProviderAccountId(baseProvider, undefined) - let requestedProviderAccountId = storedProviderAccountId - const routeMemory = thread.modelRoute ?? null - const resetReturn = routeMemory?.resetPolicy === 'return_after_reset' && - routeMemory.resetAt != null && - routeMemory.resetAt <= Date.now() && - routeMemory.failoverProviderAccountId === storedProviderAccountId && - routeMemory.preferredProviderAccountId !== storedProviderAccountId - ? { from: routeMemory.failoverProviderAccountId, to: routeMemory.preferredProviderAccountId, resetAt: routeMemory.resetAt } - : null - if (resetReturn) requestedProviderAccountId = resetReturn.to - const requestedModel = thread.model ?? (surfaceRoute && surfaceRoute.providerId === baseProvider.id ? surfaceRoute.model : null) ?? store.settings.activeModel - const threadRouteRole = thread.kind === 'chat' ? 'chat' : 'task' - if (project?.localOnly && baseProvider.kind !== 'local') { - const blockedModel = resolveProviderModel(baseProvider, requestedProviderAccountId, requestedModel) ?? requestedModel ?? store.settings.activeModel ?? baseProvider.models[0] ?? 'unknown' - const blockedRoute = modelRouter.select({ - role: threadRouteRole, - provider: baseProvider, - model: blockedModel, - requestedAccountId: requestedProviderAccountId, - allowFailover: modelRouteAutoFailoverEnabled(baseProvider, requestedProviderAccountId), - localOnly: true, - contextLimit: effectiveContextLimit(baseProvider, blockedModel, requestedProviderAccountId), - reasoningEffort: store.settings.reasoningEffort, - budget: thread.kind, - source: 'thread_local_only_guard', - }) - await auditModelRoute(thread, blockedRoute.audit) - throw new Error(blockedRoute.audit.reason) - } - const requestedProvider = await runtimeProviderWithFreshModels(baseProvider, requestedProviderAccountId) - const routeBaseProvider = store.settings.providers.find((p) => p.id === baseProvider.id) ?? baseProvider - const model = resolveProviderModel(requestedProvider, null, requestedModel) - if (!model) throw new Error('No model selected.') - if (thread.bot && model !== thread.bot.model) throw new Error('The saved bot model is unavailable; edit the bot and start a new chat.') - const initialRoute = modelRouter.select({ - role: threadRouteRole, - provider: routeBaseProvider, - model, - requestedAccountId: requestedProviderAccountId, - allowFailover: !thread.bot && modelRouteAutoFailoverEnabled(routeBaseProvider, requestedProviderAccountId), - localOnly: project?.localOnly === true, - contextLimit: effectiveContextLimit(routeBaseProvider, model, requestedProviderAccountId), - reasoningEffort: store.settings.reasoningEffort, - budget: thread.kind, - source: 'thread_initial_route', - }) - if (!initialRoute.selected) { - await auditModelRoute(thread, initialRoute.audit) - throw new Error(initialRoute.audit.reason) - } - let providerAccountId = initialRoute.selectedAccountId - let provider = providerAccountId === requestedProviderAccountId - ? requestedProvider - : await runtimeProviderWithFreshModels(routeBaseProvider, providerAccountId) - await assertProviderEndpointResolved(provider) - // Local endpoint availability (VST-015): if a local provider's server is not listening, - // refuse now with a named error instead of failing mid-run with a generic fetch error. - await assertLocalEndpointAvailable(provider) - if (thread.providerAccountId !== providerAccountId || thread.model !== model) { - const staleModel = requestedModel && requestedModel !== model ? requestedModel : null - thread.providerId = baseProvider.id - thread.providerAccountId = providerAccountId - if (resetReturn && providerAccountId === resetReturn.to) thread.modelRoute = null - thread.model = model - thread.updatedAt = Date.now() - persistThreads() - emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { providerId: thread.providerId, providerAccountId, model, modelRoute: thread.modelRoute } }) - if (staleModel) { - const notice = { id: randomUUID(), kind: 'notice' as const, text: `Model "${staleModel}" is unavailable. Switched to "${model}".`, createdAt: Date.now() } - thread.timeline.push(notice) - emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: notice }) - await auditModelRetry(thread, { - providerId: routeBaseProvider.id, - providerAccountId, - fromModel: staleModel, - toModel: model, - source: 'startup_model_resolution', - reason: `Saved model "${staleModel}" was unavailable for the selected route.`, - availableModels: provider.models, - }) - } - } - if (resetReturn && providerAccountId === resetReturn.to) { - addThreadNotice(thread, '', `Model router returned to ${modelRouteAccountLabel(routeBaseProvider, providerAccountId)} after the reset window.`) - await auditEvent('model_router.return_after_reset', { - threadId: thread.id, - providerId: routeBaseProvider.id, - model, - previousAccountId: resetReturn.from, - selectedAccountId: providerAccountId, - resetAt: resetReturn.resetAt, - }) - } - if (initialRoute.audit.action === 'failover') { - const resetAt = initialRoute.candidates.find((candidate) => candidate.accountId === initialRoute.requestedAccountId)?.exhaustedUntil ?? null - thread.modelRoute = { - preferredProviderAccountId: initialRoute.requestedAccountId, - failoverProviderAccountId: initialRoute.selectedAccountId, - resetPolicy: modelRouteResetPolicy(routeBaseProvider, initialRoute.requestedAccountId), - failedOverAt: Date.now(), - resetAt, - reason: initialRoute.audit.reason, - } - thread.updatedAt = Date.now() - persistThreads() - emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { modelRoute: thread.modelRoute } }) - addThreadNotice(thread, '', modelRouteFailoverText(routeBaseProvider, initialRoute.audit)) - await auditModelRoute(thread, initialRoute.audit) - } - if (thread.kind !== 'chat' && !botVm) thread.cwd = await resolveThreadRunCwd(thread, workspace, workspaceBoundary) - - if (controller.signal.aborted) throw new Error('Run cancelled before startup completed.') - const acceptedMemoryThread = await saveThreadMemoryPolicy(() => store.threads, thread.id, memoryPolicy, threadMemoryPolicyRevision(thread)) - const memoryRevision = threadMemoryPolicyRevision(acceptedMemoryThread) - // Publish the durable startup CAS pair before a possible Stop returns control to the UI. - emitToRenderer({ runId: '', threadId: thread.id, type: 'thread_update', patch: { memoryPolicy: { ...captureThreadMemoryPolicy(acceptedMemoryThread) }, memoryPolicyRevision: memoryRevision } }) - if (controller.signal.aborted) throw new Error('Run cancelled after memory choices were accepted.') - assertGoogleContextTransport(thread, provider) - admission?.assertAllowed() - if (quotes.length && provider.transport && provider.transport !== 'chat-completions') throw new Error('Quoted replies need a model using the TensorFold chat API.') - resolveMessageQuotes(thread, quotes) - const userContent = buildUserContent(payload.userText, attachments, quotes) - const userItem = { id: randomUUID(), kind: 'user' as const, apiMessageRef: apiUserMessageRef(thread.apiMessages, userContent, thread.compactions?.length ?? 0), memorySource: payload.sourceThreadKey ? 'external' as const : 'user' as const, text: payload.userText, attachments, ...(quotes.length ? { quotedMessages: quotes } : {}), createdAt: Date.now() } - thread.timeline.push(userItem) - thread.apiMessages.push({ role: 'user', content: userContent }) - thread.status = 'running' - thread.updatedAt = Date.now() - emitToRenderer({ runId: '', threadId: thread.id, type: 'item_add', item: userItem }) - - const runId = randomUUID() - const runMaxWallMs = 30 * 60_000 - const runContract = buildAgentRunContract({ - thread, - runId, - objective: payload.userText, - provider, - providerAccountId, - model, - approvalMode: runApprovalMode, - maxWallMs: runMaxWallMs, - }) - let job: Job | null = existingJob - ? replaceJobResult(claimJobLease(store.jobs, existingJob.id, jobLeaseOwner)) - : claimJob({ - kind: 'thread', - incognito: thread.incognito === true, - owner: thread.id, - projectId: thread.projectId ?? null, - threadId: thread.id, - currentThreadId: thread.id, - resumeAfterRestart: 'ask', - metadata: { title: thread.title, kind: thread.kind, model }, - }) - job = patchJob(job, { - currentRunId: runId, - currentThreadId: thread.id, - blockedReason: null, - executionHostId: workspace?.kind === 'ssh' ? workspace.hostId : null, - executionVerification: workspace?.kind === 'ssh' ? 'live' : null, - executionVerificationReason: workspace?.kind === 'ssh' ? 'Remote workspace connected for this run.' : null, - executionVerifiedAt: workspace?.kind === 'ssh' ? Date.now() : null, - metadata: { - currentRunId: runId, - currentThreadId: thread.id, - currentThreadTitle: thread.title, - currentThreadKind: thread.kind, - providerId: baseProvider.id, - providerAccountId, - model, - }, - }) - const jobHandle: JobHandle = { - get: () => job, - set: (next) => { job = next }, - } - - const emit = (e: AgentEvent) => { - const traced = ensureAgentEventTrace(e, 'agent.run') - applyEventToThread(thread, traced) - // Append to the crash-safe per-thread NDJSON journal: bounds data loss to the last unflushed - // event (not the last whole-thread snapshot) and gives an ordered, replayable run record. - // Encrypt the event with the app key so the on-disk journal matches threads.json's - // at-rest encryption posture (the journal holds the full plaintext transcript otherwise). - const journalEvent = thread.incognito ? null : encodeJournalEvent(traced, journalKey()) - if (journalEvent !== null) void appendThreadEvent(vontraPath('thread-journals'), thread.id, journalEvent) - emitToRenderer(traced) - } - - // Everything after the user turn belongs to this run's durable contract/receipt window. - const runTimelineStart = thread.timeline.length - emit({ runId, threadId: thread.id, type: 'thread_update', patch: { activeRunContract: runContract } }) - emit({ - runId, - threadId: thread.id, - type: 'item_add', - item: { - id: randomUUID(), - kind: 'notice', - title: 'Run contract', - text: `Run contract saved: ${runContract.surface} on ${runContract.targetKind} with ${runContract.model || 'no model'}.`, - state: 'ok', - runContract, - eventReceipt: buildEventReceipt({ - kind: 'run_contract_saved', - runId, - threadId: thread.id, - state: 'ok', - summary: 'Run contract saved before model execution.', - evidenceRefs: [runContract.id], - }), - createdAt: Date.now(), - }, - }) - - // Spend telemetry (VST-015): a near-cap budget WARNS into the timeline before the first - // model call. The hard stop needs no gate here — the initial modelRouter.select() above - // already refuses over-budget routes (applySpendControls → no_route → the throw at the - // route check), which the renderer surfaces as a visible run-refused error notice. - const initialSpend = routeSpendStatus(routeBaseProvider, providerAccountId) - if (initialSpend.warning) { - emit({ runId, threadId: thread.id, type: 'item_add', item: { id: randomUUID(), kind: 'notice', title: 'Budget', text: initialSpend.warning, state: 'ok', createdAt: Date.now() } }) - } - - if (!localHelpersOnly && !thread.googleLocalOnly && (thread.title === 'New task' || thread.title === 'New chat')) maybeAutoTitle(thread, provider, model, payload.userText) - - const routeProviderForModel = (routeProvider: Provider, routeModel: string, runModel: string) => - runModel === routeModel ? routeProvider : { ...routeProvider, models: [runModel, ...routeProvider.models.filter((candidate) => candidate !== runModel)] } - - const runWithRoute = async (route: { provider: Provider; providerAccountId: string | null; model: string }, runModel = route.model) => { - admission?.assertAllowed() - const timelineStart = thread.timeline.length - const activeProvider = routeProviderForModel(route.provider, route.model, runModel) - assertGoogleContextTransport(thread, activeProvider) - assertIncognitoThreadTransportSupported(thread, activeProvider) - if (thread.bot) { - assertBotLifecycleIdle(thread.bot.presetId) - botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) - if (botVm || restrictedBot) assertBotResearchOff(activeProvider) - } - reviewProvider = activeProvider - reviewModel = runModel - let lastJobBeat = Date.now() - const beatThreadJob = () => { - if (Date.now() - lastJobBeat < threadJobHeartbeatMs) return - lastJobBeat = Date.now() - job = heartbeatJob(job) ?? job - } - // Provider/route discovery above can take long enough for an SSH session to drop. - // Capture the tool context once at the final execution seam, validate that exact - // snapshot, and pass it through unchanged. Re-resolving later (or accepting an - // undefined backend) could reinterpret the remote path as a local lookalike. - if (thread.bot && (activeProvider.id !== thread.bot.providerId || route.providerAccountId !== thread.bot.providerAccountId || runModel !== thread.bot.model)) throw new Error('Bots keep their captured model and account; start a new bot chat to change them.') - const baseToolContext = botVm ? { cwd: '/workspace', signal: controller.signal, currentThread: thread } : fullToolContext({ thread, provider: activeProvider, model: runModel, signal: controller.signal, memoryPolicy }) - const toolContext = scopeBotToolContext(thread.bot, botVm ? createBotVmToolContext(vmHost!, thread.bot!.presetId, baseToolContext) : baseToolContext) - toolContext.memoryPolicy = memoryPolicy - assertThreadMemoryTransport(thread, activeProvider, memoryPolicy) - if (restrictedBot) toolContext.botToolScopeGuard = () => { - assertBotLifecycleIdle(thread.bot!.presetId) - botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) - assertBotResearchOff(activeProvider) - } - if (thread.incognito) toolContext.disabledToolNames = [...new Set([...toolContext.disabledToolNames ?? [], ...INCOGNITO_PERSISTENT_TOOLS])] - if (botVm) toolContext.botVm!.assertModelPrivacy = () => { - assertBotLifecycleIdle(thread.bot!.presetId) - botRunApprovalMode(thread, store.settings.agentPresets, store.settings.providers, runApprovalMode) - assertBotResearchOff(activeProvider) - } - assertSshToolContextConnected(workspace, toolContext) - const questions = getUserQuestionHost() - if (questions && thread.engine !== 'omp' && !isExternalProvider(activeProvider) && (!activeProvider.transport || activeProvider.transport === 'chat-completions')) { - toolContext.askUser = (input: UserQuestionInput, run: UserQuestionRun) => questions.ask(input, { ...run, threadId: thread.id, runId }) - } - // OMP engine threads (VST-050) run ON the installed omp coding agent via its - // headless rpc mode: omp owns the agent loop, TensorFold mirrors the timeline, plan, - // subagents, and Guide steering. The native loop below stays the default. - if (thread.engine === 'omp') { - assertOmpEngineAllowed() - const delegated = new RunRecoveryTracker(runId, snapshot => { - if (aborters.get(thread.id) !== controller) return - thread.runRecovery = snapshot; persistThreads() - emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { runRecovery: snapshot } }) - }) - const activeTools = new Set>() - let acceptingTools = true, delegatedComplete = false - const stopDelegated = () => delegated.stopRequested() - delegated.start(); delegated.begin('delegated'); delegated.requestStarted() - controller.signal.addEventListener('abort', stopDelegated, { once: true }) - try { await runOmpThread({ - thread, - runId, - emit: (event) => { emit(event); beatThreadJob() }, - signal: controller.signal, - persist: persistThreads, - userText: payload.userText, - approvalMode: runApprovalMode, - reasoningEffort: store.settings.reasoningEffort, - drainCues: () => drainThreadCues(thread.id), - onSession: (cursor) => { thread.ompResumeCursor = cursor }, - // Host-tools bridge: omp's model plans, TensorFold's approval gate and executor - // own every mutation (write_file/edit_file/apply_patch/run_command). - requestApproval: approvalResolver(controller, jobHandle), - executeTool: async (name, args) => { - if (!acceptingTools) throw new Error('The delegated run is stopping; no further tools can start.') - const operation = randomUUID(), mutating = !isReadOnlyTool(name) - delegated.begin(operation, mutating) - const pending = executeTool(name, args, { ...toolContext, currentThread: thread, signal: controller.signal }) - activeTools.add(pending) - try { const result = await pending; delegated.toolCompleted(mutating, result.ok); return result } - catch (error) { if (mutating) delegated.toolUncertain(); throw error } - finally { activeTools.delete(pending); delegated.end(operation) } - }, - updateSubAgent: (record) => { - const existing = store.subAgents.find((agent) => agent.id === record.id) - if (existing) { - const updated = updateSubAgent(store.subAgents, record.id, { status: record.status, name: record.name, task: record.task }) - if (updated.agent) store.subAgents = updated.agents - } else { - const created = createSubAgentFromLaunch(store.subAgents, { - source: 'thread_tool', - parent: parentForThread(thread), - task: record.task, - name: record.name, - providerId: activeProvider.id, - providerAccountId, - model: runModel, - runId: `omp-${record.id}`, - cwd: thread.cwd, - }) - // omp mints its own stable subagent ids; keep them as the TensorFold ids so - // later snapshots update the same records. - created.agent.id = record.id - store.subAgents = created.agents - } - void saveSubAgents(store.subAgents) - }, - }); delegated.requestComplete(); delegatedComplete = true - } catch (error) { delegated.requestFailed('unknown'); throw error } - finally { - acceptingTools = false - await Promise.allSettled([...activeTools]) - delegated.end('delegated'); delegated.settle(delegatedComplete) - controller.signal.removeEventListener('abort', stopDelegated) - } - } else { - await runAgent({ - responseLocale: selectedResponseLocale(store.settings.uiPreferences), - onRecovery: snapshot => { - if (aborters.get(thread.id) !== controller) return - thread.runRecovery = snapshot - persistThreads() - emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { runRecovery: snapshot } }) - }, - assertRequestAllowed: () => { admission?.assertAllowed(); assertGoogleContextTransport(thread, activeProvider) }, - thread, - provider: activeProvider, - model: runModel, - runId, - approvalMode: runApprovalMode, - temperature: store.settings.temperature, - reasoningEffort: store.settings.reasoningEffort, - serviceTier: store.settings.serviceTier, - autoCompact: store.settings.autoCompact, - contextLimit: effectiveContextLimit(activeProvider, runModel), - toolContext, - observe: thread.incognito ? undefined : deps.observe, - pluginRuntime: thread.incognito ? new PluginRuntime() : undefined, - drainCues: () => drainThreadCues(thread.id), - waitForCue: (timeoutMs, signal) => waitForThreadCue(thread.id, timeoutMs, signal), - memoryPolicy, - projectMemory: botVm || !memoryPolicy.useExisting ? '' : renderProjectMemoryBucket(store.projects.find((p) => p.id === thread.projectId), payload.userText), - // Resolve the persona fresh each run (hot reload) for this thread's scope. - personaBlock: thread.bot ? botInstructions(thread.bot) : personaSystemBlock( - resolvePersona(store.settings.personas ?? [], { isAssistant: thread.kind === 'chat', workspaceId: thread.projectId ?? null }), - { userProfile: store.settings.userProfile }, - ), - // Per-channel ephemeral prompt: when this run acts on a connector conversation, inject - // that source's channelPrompt for this run only (never into the persisted snapshot). - channelPrompt: selectChannelPrompt(payload.sourceThreadKey, store.settings) ?? undefined, - // File durable facts salvaged at compaction as pending project-memory candidates - // (project-scoped; skipped for project-less chat threads). - onMemoryHarvest: (candidates) => { - if (thread.googleLocalOnly || !canContributeThreadMemory(thread, memoryPolicy, memoryRevision, controller.signal) || !store.threads.includes(thread) || !thread.projectId || !candidates.length) return - const authored = projectMemoryAutoMessages(store.projectMemory, thread) - for (const text of candidates) { - const sourceTurn = projectMemoryAutoCandidateTurn(authored, text) - if (sourceTurn === null) continue - store.projectMemoryCandidates = [createProjectMemoryCandidate({ projectId: thread.projectId, text, sourceType: 'agent', reason: 'Salvaged from the conversation at compaction.', sourceThreadId: thread.id, sourceTurn }), ...store.projectMemoryCandidates] - } - persistProjectMemoryCandidates() - }, - onProviderRateLimits: deps.recordProviderRateLimits, - guardPolicy: runContract.guardPolicy, - maxSteps: runContract.guardPolicy.maxSteps, - maxWallMs: runMaxWallMs, - emit: (event) => { emit(event); beatThreadJob() }, - signal: controller.signal, - requestApproval: approvalResolver(controller, jobHandle), - auditToolCall: async ({ tool, args, resultOk, output }) => { - // Note skills the agent actually read this run — the post-run review only looks at these. - if (tool === 'skill_view' && resultOk && args?.name) viewedSkillNames.add(String(args.name)) - if (isHighRiskTool(tool)) await auditEvent('agent.tool', { threadId: thread.id, runId, tool, ok: resultOk, ...(thread.incognito ? {} : { cwd: auditPreview(thread.cwd), args: auditPreview(JSON.stringify(args)), output: auditPreview(output) }) }) - }, - persist: persistThreads, - }) - } - const errorItem = timelineErrorSince(thread, timelineStart) - if (errorItem && !controller.signal.aborted) throw timelineError(errorItem) - } - - let activeRoute = { provider, providerAccountId, model } - // Scope the run's success/failure to items THIS run appends — a leftover error item from a - // previous run must not mark a later successful run as failed (which stalls the PR loop). - - // Skill self-improvement bookkeeping: which skills the agent consulted this run, and the - // provider/model it ran on (so the post-run review reuses the same backend). Populated in - // auditToolCall + runWithRoute; consumed in the .finally review pass. - const viewedSkillNames = new Set() - let reviewProvider: Provider | null = null - let reviewModel = '' - - // Repo-authored skills rescan (VST-010): awaited so this run's context reflects the - // trust state of the content on disk RIGHT NOW (a just-edited trusted skill drops out - // until re-reviewed). Missing dirs and scan errors degrade to "no project skills". - if (deps.refreshProjectSkills && thread.projectId) { - const project = store.projects.find((p) => p.id === thread.projectId) - if (project) await deps.refreshProjectSkills({ id: project.id, cwd: project.cwd, workspace }).catch(() => {}) - } - - // Finish the pre-turn file snapshot before the model can invoke a write tool. - // Capture remains best-effort, but fire-and-forget here would race a fast local - // model and could accidentally snapshot post-edit state. The returned SHA ties - // the conversation record to a file ref only when capture really succeeded. - const checkpointTurn = threadTurnNumber(thread.timeline) - await recordPreTurnCheckpoint({ - threadId: thread.id, - incognito: thread.incognito, - turn: checkpointTurn, - target: { cwd: thread.cwd, workspace, kind: thread.kind }, - conversation: { - apiMessages: thread.apiMessages ?? [], - timeline: thread.timeline ?? [], - goal: thread.goal, - goalStatus: (thread as { goalStatus?: string }).goalStatus, - plan: (thread as { plan?: unknown[] }).plan, - status: thread.status, - }, - }, deps) - - runWithRoute(activeRoute) - .catch(async (err) => { - const liveModels = availableModelsFromProviderError(err) - const fallbackModel = liveModels.find((candidate) => candidate !== activeRoute.model) - if (fallbackModel && thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && !thread.bot && !controller.signal.aborted) { - const rejectedModel = activeRoute.model - markRouteErrorRecovered(thread, err, runId, `Model "${rejectedModel}" was rejected by ${baseProvider.name}; retrying with "${fallbackModel}".`) - rememberProviderModels(baseProvider.id, activeRoute.providerAccountId, liveModels) - activeRoute = { ...activeRoute, model: fallbackModel } - thread.model = fallbackModel - thread.updatedAt = Date.now() - persistThreads() - emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { model: fallbackModel } }) - const notice = { id: randomUUID(), kind: 'notice' as const, text: `Model "${rejectedModel}" was rejected by ${baseProvider.name}. Retrying with "${fallbackModel}".`, createdAt: Date.now() } - thread.timeline.push(notice) - emitToRenderer({ runId, threadId: thread.id, type: 'item_add', item: notice }) - await auditModelRetry(thread, { - providerId: baseProvider.id, - providerAccountId: activeRoute.providerAccountId, - fromModel: rejectedModel, - toModel: fallbackModel, - source: 'provider_available_models', - reason: `Provider rejected model "${rejectedModel}" and returned live alternatives.`, - availableModels: liveModels, - }) - try { - await runWithRoute(activeRoute, fallbackModel) - } catch (retryErr) { - emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((retryErr as any)?.message ?? retryErr) }) - } - return - } - // The route-recovery setup below performs un-try-caught awaits (audit, provider refresh, - // and assertProviderEndpointResolved — which throws when a failover endpoint resolves to a - // private IP). Without this guard a throw here rejects the catch callback itself; the chain - // has no further .catch, so it becomes an unhandled rejection and the user sees the run - // silently die. Wrap it so any failure surfaces as the same user-facing error event the - // non-recovered path emits, then fall through to the shared .finally. - try { - const latestBaseProvider = store.settings.providers.find((p) => p.id === baseProvider.id) ?? baseProvider - const routed = modelRouter.routeAfterError({ - role: threadRouteRole, - provider: latestBaseProvider, - accountId: activeRoute.providerAccountId, - model: activeRoute.model, - error: err, - allowFailover: thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && !thread.bot && (modelRouteAutoFailoverEnabled(latestBaseProvider, activeRoute.providerAccountId) || thread.modelRoute?.resetPolicy === 'rotate_on_limit'), - localOnly: project?.localOnly === true, - contextLimit: effectiveContextLimit(latestBaseProvider, activeRoute.model, activeRoute.providerAccountId), - reasoningEffort: store.settings.reasoningEffort, - budget: thread.kind, - source: 'thread_recovery', - }) - if (routed.signal) { - for (const audit of routed.audit) await auditModelRoute(thread, audit, routed.signal) - } - if (thread.runRecovery?.runId === runId && thread.runRecovery.retry === 'safe' && routed.signal && routed.route.selected && routed.route.selectedAccountId !== activeRoute.providerAccountId && !controller.signal.aborted) { - markRouteErrorRecovered(thread, err, runId, `Recovered provider limit on ${modelRouteAccountLabel(latestBaseProvider, activeRoute.providerAccountId)} for ${activeRoute.model}; retrying on ${modelRouteAccountLabel(latestBaseProvider, routed.route.selectedAccountId)}.`) - const exhaustedAccountId = activeRoute.providerAccountId - providerAccountId = routed.route.selectedAccountId - provider = await runtimeProviderWithFreshModels(latestBaseProvider, providerAccountId) - await assertProviderEndpointResolved(provider) - activeRoute = { provider, providerAccountId, model: activeRoute.model } - thread.providerId = latestBaseProvider.id - thread.providerAccountId = providerAccountId - thread.model = activeRoute.model - thread.modelRoute = { - preferredProviderAccountId: exhaustedAccountId, - failoverProviderAccountId: providerAccountId, - resetPolicy: modelRouteResetPolicy(latestBaseProvider, exhaustedAccountId), - failedOverAt: Date.now(), - resetAt: routed.signal.resetAt, - reason: routed.route.audit.reason, - } - thread.updatedAt = Date.now() - persistThreads() - emitToRenderer({ runId, threadId: thread.id, type: 'thread_update', patch: { providerId: thread.providerId, providerAccountId, model: activeRoute.model, modelRoute: thread.modelRoute } }) - addThreadNotice(thread, runId, modelRouteFailoverText(latestBaseProvider, routed.route.audit, routed.signal)) - injectThreadRouteHandoff(thread, `Thread "${thread.title}" failed over after ${routed.signal.kind.replace(/_/g, ' ')}.`) - try { - await runWithRoute(activeRoute) - } catch (retryErr) { - emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((retryErr as any)?.message ?? retryErr) }) - } - return - } - emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String(err?.message ?? err) }) - } catch (recoveryErr) { - // Recovery setup itself failed — surface the original error plus the recovery failure. - emitToRenderer({ runId, threadId: thread.id, type: 'error', message: String((recoveryErr as any)?.message ?? recoveryErr) }) - } - }) - .finally(() => { - markUndrainedCues(thread, controller.signal.aborted ? 'canceled' : 'run ended') - const failed = !!timelineErrorSince(thread, runTimelineStart) - const remoteTransport = workspace?.kind === 'ssh' && workspace.hostId && sshManager.status ? sshManager.status(workspace.hostId) : null - const transportUnverifiable = failed && !!remoteTransport && (remoteTransport.phase === 'disconnected' || remoteTransport.phase === 'error') - if (transportUnverifiable && workspace?.kind === 'ssh') { - const reason = remoteTransport?.lastError - ? `Remote transport lost: ${remoteTransport.lastError}` - : 'Remote transport lost; the process state is unverifiable.' - job = patchJob(job, { - executionVerification: 'unverifiable', - executionVerificationReason: reason, - executionVerifiedAt: Date.now(), - }) - } - const recoveryPaused = thread.runRecovery?.runId === runId && ['paused', 'needs_review'].includes(thread.runRecovery.state) - const receipt = buildAgentRunReceipt({ thread, contract: runContract, timelineStart: runTimelineStart, aborted: controller.signal.aborted }) - const turnReceipt = buildEventReceipt({ - kind: 'turn_complete', - runId, - threadId: thread.id, - state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', - summary: receipt.summary, - evidenceRefs: [receipt.id], - }) - const jobReceipt = buildEventReceipt({ - kind: 'job_complete', - runId, - threadId: thread.id, - state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', - summary: `Thread job finished with ${receipt.verdict}.`, - evidenceRefs: [receipt.id], - }) - const savedReceipt = buildEventReceipt({ - kind: 'run_receipt_saved', - runId, - threadId: thread.id, - state: controller.signal.aborted ? 'cancelled' : failed ? 'error' : receipt.needsReview || recoveryPaused ? 'blocked' : 'ok', - summary: 'Run receipt saved at run end.', - evidenceRefs: [receipt.id], - }) - receipt.eventReceipts.push(turnReceipt, jobReceipt, savedReceipt) - emit({ runId, threadId: thread.id, type: 'thread_update', patch: { activeRunContract: null, lastRunReceipt: receipt } }) - emit({ - runId, - threadId: thread.id, - type: 'item_add', - item: { - id: randomUUID(), - kind: 'notice', - title: 'Run receipt', - text: `Run receipt: ${receipt.verdict}. ${receipt.summary}`, - state: receipt.needsReview ? 'awaiting' : 'ok', - runReceipt: receipt, - eventReceipt: savedReceipt, - createdAt: Date.now(), - }, - }) - thread.status = failed ? 'error' : 'idle' - thread.updatedAt = Date.now() - // Only retire our own controller — never clobber a controller a later run installed. - if (aborters.get(thread.id) === controller) aborters.delete(thread.id) - runLease.release() - releaseBotVmRun() - settleThreadRunJob( - job, - thread, - controller.signal.aborted || transportUnverifiable || recoveryPaused ? 'paused' : failed ? 'failed' : 'completed', - transportUnverifiable - ? 'Remote transport disconnected; execution is unverifiable and must be reconciled after reconnecting.' - : recoveryPaused ? thread.runRecovery?.message : failed ? 'Thread agent run ended with an error.' : undefined, - ) - persistThreads() - // Bound the per-thread NDJSON journal: high-frequency item_delta chunks make it grow - // without limit since compactThreadJournal was never called in production. At run-end the - // events are already folded into the persisted thread snapshot, so keep only a recent tail - // for crash replay. Fire-and-forget; failures must not affect run settlement. - if (!thread.incognito) void compactThreadJournalTail(thread.id) - - // Skill self-improvement (opt-in): on a successful run that consulted a skill, let an - // aux model review those skills and FILE improvement suggestions (consent-first; never - // auto-applied). Fully fire-and-forget — it must never disturb the settled run. - if (!localHelpersOnly && !thread.phoneLocalOnly && !thread.googleLocalOnly && canContributeThreadMemory(thread, memoryPolicy, memoryRevision, controller.signal) && store.settings.skillSelfImprovement && !failed && !recoveryPaused && !controller.signal.aborted && viewedSkillNames.size && reviewProvider) { - void reviewViewedSkills({ provider: reviewProvider, model: reviewModel, thread, userText: payload.userText, viewed: [...viewedSkillNames], signal: controller.signal, memoryPolicy, memoryRevision }) - } - if (!failed && !recoveryPaused && !controller.signal.aborted) { - try { proposePostRunMemory(thread, memoryPolicy, memoryRevision, controller.signal) } catch { /* best effort — never disturb the settled run */ } - } - }) - // Backstop: every awaited path inside .catch/.finally is itself guarded, but attach a - // terminal handler so no recovery/journal failure can ever escape as an unhandled rejection. - .catch(() => { - if (aborters.get(thread.id) === controller) aborters.delete(thread.id) - runLease.release() - releaseBotVmRun() - }) - - return { runId } - } catch (err) { - if (aborters.get(thread.id) === controller) aborters.delete(thread.id) - runLease.release() - releaseBotVmRun() - throw err - } - } - function applyEventToThread(thread: Thread, e: AgentEvent) { if (e.type === 'item_add') { ensureTimelineItemTrace(e.item, { runId: e.runId, threadId: thread.id, parentTraceId: e.trace?.parentTraceId ?? null, origin: e.trace?.origin ?? 'agent.event' }) @@ -1279,6 +387,23 @@ export function createThreadRuntime(deps: ThreadRuntimeDeps): ThreadRuntime { cueWaiters.clear() } + const startThreadRun = createThreadRunStarter(deps, { + addThreadNotice, + applyEventToThread, + drainThreadCues, + waitForThreadCue, + timelineErrorSince, + timelineError, + markRouteErrorRecovered, + markUndrainedCues, + injectThreadRouteHandoff, + availableModelsFromProviderError, + compactThreadJournalTail, + reviewViewedSkills, + proposePostRunMemory, + maybeAutoTitle, + }) + return { addThreadNotice, applyEventToThread, diff --git a/app/electron/main/host/ticket-ready-release.test.ts b/app/electron/main/host/ticket-ready-release.test.ts new file mode 100644 index 00000000000..284327d93ed --- /dev/null +++ b/app/electron/main/host/ticket-ready-release.test.ts @@ -0,0 +1,65 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import ts from 'typescript' +import { pickTicketUserPatch, assertTicketUserUpdateAllowed } from './room-ticket-patch-policy' +import { assertTicketRelations } from './ticket-helpers' +import { normalizeTicketExecution } from '../../agent/tickets' + +function declaration(file: string, match: (node: ts.Node) => boolean): string { + const tree = ts.createSourceFile(file, readFileSync(file, 'utf8'), ts.ScriptTarget.ES2022, true) + const found: ts.Node[] = [] + const visit = (node: ts.Node) => { if (match(node)) found.push(node); ts.forEachChild(node, visit) } + visit(tree) + assert.equal(found.length, 1, 'extract the actual production handler exactly once') + const node = ts.isCallExpression(found[0]) ? found[0].arguments[1] : found[0] + return ts.createPrinter().printNode(ts.EmitHint.Unspecified, node, tree) +} +const local = declaration(path.join(__dirname, 'workspace-runtime-ipc.ts'), (node) => ts.isCallExpression(node) && ts.isIdentifier(node.expression) && node.expression.text === 'handle' && ts.isStringLiteral(node.arguments[0]) && node.arguments[0].text === 'tickets:update') +const remote = declaration(path.join(__dirname, 'remote-host-api.ts'), (node) => ts.isFunctionDeclaration(node) && node.name?.text === 'updateTicketOnThisHost') + +for (const [surface, source] of [['local', local], ['remote', remote]]) { + const ticket: any = { id: 'ticket', projectId: 'project', roomId: 'room', title: 'Synthetic', body: '', type: 'task', status: 'in_progress', priority: 'medium', effort: 'small', tags: [], assignee: 'Builder', threadId: 'thread', runState: null, evidence: [], createdAt: 1, updatedAt: 1 } + const store: any = { tickets: [ticket], projects: [{ id: 'project' }], rooms: [{ id: 'room', projectId: 'project' }], threads: [{ id: 'thread', projectId: 'project' }] } + const aborters = new Map(), published: unknown[] = [] + let starting = false, persisted = 0 + const bindings = { + store, pickTicketUserPatch, assertTicketUserUpdateAllowed, assertTicketRelations, normalizeTicketExecution, + requireSecurityRole() {}, aborters, isTicketStarting: () => starting, + normalizeStringList: (value: string[]) => value, + persistTickets: () => persisted++, emitTicket: (value: unknown) => published.push(structuredClone(value)), + deps: { aborters: () => aborters, ticketWorkerRuntime: () => ({ isTicketStarting: () => starting }), emitTicket: (value: unknown) => published.push(structuredClone(value)) }, + validateTicketOwnershipOnThisHost: (projectId: string, roomId: string, options: any) => assertTicketRelations(store, projectId, roomId, options), + remoteMutationError: (message: string, status = 409) => Object.assign(new Error(message), { status }), + } + const code = surface === 'local' ? `const handler = ${source};` : `${source}; const handler = updateTicketOnThisHost;` + const compiled = ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None } }).outputText + const handler = new Function(...Object.keys(bindings), `${compiled}; return handler;`)(...Object.values(bindings)) + const invoke = (patch: unknown) => surface === 'local' ? handler(null, { id: ticket.id, patch }) : handler(ticket.id, patch) + + const next = await invoke({ status: 'ready' }) + assert.equal(next.assignee, null, `${surface}: returning a parked ticket to Ready must release its previous owner`) + assert.equal(next.threadId, 'thread', 'release preserves the existing worker chat/history') + assert.equal(persisted, 1) + assert.equal((published[0] as any).assignee, null, 'the released claim is published to clients') + ticket.assignee = 'Reviewer' + await invoke({ priority: 'high' }) + assert.equal(ticket.assignee, 'Reviewer', 'ordinary edits never change ticket ownership') + for (const runState of ['queued', 'running', null]) { + ticket.runState = runState + if (runState === null) aborters.set('thread', {}) + await assert.rejects(invoke({ status: 'ready' }), /Stop the active ticket/) + assert.equal(ticket.assignee, 'Reviewer', 'a rejected transition must not clear a live claim') + aborters.clear() + } + ticket.runState = null; starting = true + await assert.rejects(invoke({ status: 'ready' }), /Stop the active ticket/) + starting = false + for (const patch of [{ assignee: 'Another' }, { status: 'ready', assignee: null }]) { + await assert.rejects(invoke(patch), /assignee cannot be changed/, 'clients cannot forge host-owned ownership fields') + } + ticket.archivedAt = 2 + await assert.rejects(invoke({ status: 'ready' }), /archived/) + assert.equal(ticket.assignee, 'Reviewer') +} +console.log('Local/remote Ready transitions release parked claims, preserve history and retain active/startup/archive/privileged-field guards') diff --git a/app/electron/main/host/usability-integration.test.ts b/app/electron/main/host/usability-integration.test.ts index b94efacc74f..1c95bd75870 100644 --- a/app/electron/main/host/usability-integration.test.ts +++ b/app/electron/main/host/usability-integration.test.ts @@ -1,15 +1,17 @@ import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import ts from 'typescript' +import { botRunReasoningEffort } from '../../../shared/bot-reasoning' // Execute the production asynchronous recovery callback with inert host adapters. // This isolates the routing authority seam without starting an app/model/runtime. function recoveryHandler(environment: Record) { - const source = readFileSync('electron/main/host/thread-runtime.ts', 'utf8') + environment = { botRunReasoningEffort, ...environment } + const source = readFileSync('electron/main/host/thread-run-settlement.ts', 'utf8') const file = ts.createSourceFile('thread-runtime.ts', source, ts.ScriptTarget.ES2022, true) let callback = '' const visit = (node: ts.Node) => { - if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'catch' && node.expression.expression.getText(file) === 'runWithRoute(activeRoute)') callback = node.arguments[0].getText(file) + if (ts.isCallExpression(node) && ts.isPropertyAccessExpression(node.expression) && node.expression.name.text === 'catch' && node.expression.expression.getText(file) === 'pending') callback = node.arguments[0].getText(file) ts.forEachChild(node, visit) } visit(file); assert.ok(callback, 'The actual route-recovery callback is reviewed') @@ -45,7 +47,8 @@ console.log('Actual route-recovery callback binds retry authority to current run const { RunRecoveryTracker } = await import('../../agent/run-recovery/tracker') function delegatedHandler(environment: Record) { - const source = readFileSync('electron/main/host/thread-runtime.ts', 'utf8'), ast = ts.createSourceFile('runtime.ts', source, ts.ScriptTarget.ES2022, true) + environment = { botRunReasoningEffort, ...environment } + const source = readFileSync('electron/main/host/thread-run-execution.ts', 'utf8'), ast = ts.createSourceFile('runtime.ts', source, ts.ScriptTarget.ES2022, true) let body = '' const visit = (node: ts.Node) => { if (ts.isIfStatement(node) && node.expression.getText(ast) === "thread.engine === 'omp'") body = node.thenStatement.getText(ast); ts.forEachChild(node, visit) } visit(ast); assert.ok(body) @@ -217,7 +220,7 @@ await assert.rejects(reviewing, /changed/); assert.throws(() => assertRecoveryAl console.log('Actual main outcome-review callback refuses wrong/active/draining runs and stale persistence completion, preserves history and cannot authorize a newer uncertain run.') const { buildAgentRunContract, buildAgentRunReceipt, buildEventReceipt } = await import('../../agent/run-contract') -const runtimeSource = readFileSync('electron/main/host/thread-runtime.ts', 'utf8') +const runtimeSource = readFileSync('electron/main/host/thread-run-settlement.ts', 'utf8') const receiptStart = runtimeSource.indexOf('const recoveryPaused = thread.runRecovery'), receiptEnd = runtimeSource.indexOf('receipt.eventReceipts.push(turnReceipt, jobReceipt, savedReceipt)', receiptStart) assert.ok(receiptStart > 0 && receiptEnd > receiptStart) const receiptFragment = runtimeSource.slice(receiptStart, receiptEnd) + 'return { receipt, turnReceipt, jobReceipt, savedReceipt };' diff --git a/app/native/computer-use/ComputerUseChecks/.gitignore b/app/native/computer-use/ComputerUseChecks/.gitignore new file mode 100644 index 00000000000..2d9f16e2d27 --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/.gitignore @@ -0,0 +1,2 @@ +.build/ +.swiftpm/ diff --git a/app/native/computer-use/ComputerUseChecks/Package.swift b/app/native/computer-use/ComputerUseChecks/Package.swift new file mode 100644 index 00000000000..923eab31ada --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/Package.swift @@ -0,0 +1,10 @@ +// swift-tools-version: 6.2 +import PackageDescription + +let package = Package( + name: "ComputerUseChecks", + targets: [ + .target(name: "ComputerUseChecks"), + .testTarget(name: "ComputerUseChecksTests", dependencies: ["ComputerUseChecks"]), + ] +) diff --git a/app/native/computer-use/ComputerUseChecks/README.md b/app/native/computer-use/ComputerUseChecks/README.md new file mode 100644 index 00000000000..870c08a50cd --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/README.md @@ -0,0 +1,11 @@ +# ComputerUseChecks + +Run the shared parser, key-table, phone-input validation and JSON-line checks with Swift 6.2 or later on macOS or Linux: + +```sh +swift test --package-path app/native/computer-use/ComputerUseChecks +``` + +The Mac helper compiles these same `Sources/ComputerUseChecks` files directly. Package tests, the manifest and `.build` artifacts are excluded from that binary. Linux uses Foundation geometry and small key-code/event-flag stand-ins; macOS uses CoreGraphics. + +Click execution, screen inspection, native phone-window checks and OCR stay in the Mac helper. From `app/`, build it and run its remaining self-checks with `npm run build:computer-helper`. diff --git a/app/native/computer-use/Keys.swift b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Keys.swift similarity index 97% rename from app/native/computer-use/Keys.swift rename to app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Keys.swift index d2a926eb337..bf136f49d56 100644 --- a/app/native/computer-use/Keys.swift +++ b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Keys.swift @@ -1,6 +1,9 @@ +import Foundation +#if canImport(CoreGraphics) import CoreGraphics +#endif -struct Modifier: Equatable { +struct Modifier: Equatable, Sendable { let flag: CGEventFlags // nil for fn: a lone fn press can open the emoji picker or dictation, so it only sets the flag. let keyCode: CGKeyCode? diff --git a/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/PhoneValidation.swift b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/PhoneValidation.swift new file mode 100644 index 00000000000..ed1544a1c2e --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/PhoneValidation.swift @@ -0,0 +1,11 @@ +import Foundation + +func phoneLocalPoint(_ point: CGPoint, size: CGSize) -> Bool { + point.x.isFinite && point.y.isFinite && size.width.isFinite && size.height.isFinite && size.width >= 1 && size.height >= 1 && point.x >= 0 && point.y >= 0 && point.x < size.width && point.y < size.height +} + +func phoneTypeAllowed(_ text: String) -> Bool { + text.unicodeScalars.allSatisfy { scalar in + scalar == "\n" || scalar == "\t" || scalar.value >= 32 && scalar.value != 127 && !(0xE000...0xF8FF).contains(scalar.value) + } +} diff --git a/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Platform.swift b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Platform.swift new file mode 100644 index 00000000000..23ba7a3cc0f --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Platform.swift @@ -0,0 +1,15 @@ +#if !canImport(CoreGraphics) +typealias CGKeyCode = UInt16 + +// Linux only needs the flag values; Foundation supplies CGPoint and CGSize on both platforms. +struct CGEventFlags: OptionSet, Sendable { + let rawValue: UInt64 + init(rawValue: UInt64) { self.rawValue = rawValue } + + static let maskShift = Self(rawValue: 1 << 17) + static let maskControl = Self(rawValue: 1 << 18) + static let maskAlternate = Self(rawValue: 1 << 19) + static let maskCommand = Self(rawValue: 1 << 20) + static let maskSecondaryFn = Self(rawValue: 1 << 23) +} +#endif diff --git a/app/native/computer-use/Protocol.swift b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Protocol.swift similarity index 97% rename from app/native/computer-use/Protocol.swift rename to app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Protocol.swift index 5abd28f252b..7db6d185da5 100644 --- a/app/native/computer-use/Protocol.swift +++ b/app/native/computer-use/ComputerUseChecks/Sources/ComputerUseChecks/Protocol.swift @@ -1,5 +1,8 @@ -import CoreGraphics +import CoreFoundation import Foundation +#if canImport(CoreGraphics) +import CoreGraphics +#endif struct HelperError: Error { let code: String @@ -203,11 +206,11 @@ func parseCommand(_ cmd: String, _ p: Params) throws -> Command { return .drag(try p.point("from"), try p.point("to")) case "scroll": let at = try p.target() - let dx = Int((try p.number("dx") ?? 0).rounded()) - let dy = Int((try p.number("dy") ?? 0).rounded()) + let dx = (try p.number("dx") ?? 0).rounded() + let dy = (try p.number("dy") ?? 0).rounded() guard dx != 0 || dy != 0 else { throw badRequest("scroll needs a non-zero dx or dy.") } - guard abs(dx) <= maxScrollLines, abs(dy) <= maxScrollLines else { throw badRequest("scroll is limited to \(maxScrollLines) lines per call.") } - return .scroll(at, dx: dx, dy: dy) + guard abs(dx) <= Double(maxScrollLines), abs(dy) <= Double(maxScrollLines) else { throw badRequest("scroll is limited to \(maxScrollLines) lines per call.") } + return .scroll(at, dx: Int(dx), dy: Int(dy)) case "type": guard let text = try p.string("text"), !text.isEmpty else { throw badRequest("type needs non-empty text.") } guard text.count <= maxTypeCharacters else { throw badRequest("type is limited to \(maxTypeCharacters) characters per call.") } diff --git a/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/KeysTests.swift b/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/KeysTests.swift new file mode 100644 index 00000000000..0322cd53f98 --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/KeysTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +#if canImport(CoreGraphics) +import CoreGraphics +#endif +@testable import ComputerUseChecks + +struct KeysTests { + @Test func keyCodesAliasesAndModifiers() throws { + let good: [(String, CGKeyCode, CGEventFlags)] = [ + ("cmd+shift+t", 17, [.maskCommand, .maskShift]), ("Return", 36, []), ("enter", 36, []), + ("ctrl+opt+delete", 51, [.maskControl, .maskAlternate]), ("command+alt+esc", 53, [.maskCommand, .maskAlternate]), + ("f12", 111, []), ("F1", 122, []), ("cmd+,", 43, [.maskCommand]), ("cmd+=", 24, [.maskCommand]), + ("shift+`", 50, [.maskShift]), ("pagedown", 121, []), ("pageup", 116, []), ("fn+f1", 122, [.maskSecondaryFn]), + (" cmd + a ", 0, [.maskCommand]), ("cmd+cmd+a", 0, [.maskCommand]), ("space", 49, []), ("up", 126, []), + ("down", 125, []), ("left", 123, []), ("right", 124, []), ("home", 115, []), ("end", 119, []), + ("forwarddelete", 117, []), ("backspace", 51, []), ("tab", 48, []), ("control+[", 33, [.maskControl]), + ("cmd+]", 30, [.maskCommand]), ("ctrl+;", 41, [.maskControl]), ("'", 39, []), ("/", 44, []), (".", 47, []), + ("-", 27, []), ("0", 29, []), ("9", 25, []), ("z", 6, []), ("option+shift+k", 40, [.maskAlternate, .maskShift]), + ] + for (text, code, flags) in good { + let combo = try parseKeyCombo(text) + #expect(combo.keyCode == code, "key \(text) code") + #expect(combo.flags == flags, "key \(text) flags") + } + let order = try parseKeyCombo("shift+cmd+t") + #expect(order.modifiers.map { $0.keyCode } == [56, 55], "modifiers keep their order") + let repeated = try parseKeyCombo("cmd+cmd+a") + #expect(repeated.modifiers.count == 1, "a repeated modifier is pressed once") + let fn = try parseKeyCombo("fn+f1") + let modifier = try #require(fn.modifiers.first) + #expect(modifier.keyCode == nil, "fn only sets a flag") + #expect(CGEventFlags.maskShift.rawValue == 1 << 17) + #expect(CGEventFlags.maskControl.rawValue == 1 << 18) + #expect(CGEventFlags.maskAlternate.rawValue == 1 << 19) + #expect(CGEventFlags.maskCommand.rawValue == 1 << 20) + #expect(CGEventFlags.maskSecondaryFn.rawValue == 1 << 23) + let printable: [(String, Bool)] = [("a", true), ("shift+a", true), ("space", true), ("cmd+a", false), ("ctrl+c", false), ("return", false), ("left", false), ("tab", false)] + for (text, expected) in printable { + let combo = try parseKeyCombo(text) + #expect(comboTypesCharacter(combo) == expected, "\(text) types a character: \(expected)") + } + } + + @Test func invalidKeysAreRejected() { + let bad = ["", " ", "cmd", "cmd+shift", "cmd+foo", "a+b", "f13", "hyper+a", "cmd++", "+", "control+option+", String(repeating: "a", count: 100)] + for text in bad { + do { + _ = try parseKeyCombo(text) + Issue.record("key \(text.prefix(20)) should fail") + } catch let error as HelperError { + #expect(error.code == "bad_key", "key \(text.prefix(20)) fails with bad_key") + } catch { + Issue.record("key \(text.prefix(20)) threw something else") + } + } + } +} diff --git a/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/ProtocolTests.swift b/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/ProtocolTests.swift new file mode 100644 index 00000000000..1e1e2a62f27 --- /dev/null +++ b/app/native/computer-use/ComputerUseChecks/Tests/ComputerUseChecksTests/ProtocolTests.swift @@ -0,0 +1,122 @@ +import Foundation +import Testing +@testable import ComputerUseChecks + +func failureCode(_ line: String) -> String? { + if case .failure(let error) = parseRequest(line).command { return error.code } + return nil +} + +func parsedCommand(_ line: String) -> Command? { + if case .success(let command) = parseRequest(line).command { return command } + return nil +} + +struct ProtocolTests { + @Test func requestsParse() { + let permissions = parseRequest(#"{"id":1,"cmd":"permissions"}"#) + #expect(permissions.id == 1, "id is read") + #expect(parsedCommand(#"{"id":1,"cmd":"permissions"}"#) == .permissions, "permissions parses") + let good: [(String, Command)] = [ + (#"{"id":1,"cmd":"click","x":10,"y":20}"#, .click(.point(CGPoint(x: 10, y: 20)), .left, 1)), + (#"{"id":1,"cmd":"click","element":4,"button":"right","count":2}"#, .click(.element(4), .right, 2)), + (#"{"id":1,"cmd":"observe"}"#, .observe(maxElements: 150, pid: nil)), + (#"{"id":1,"cmd":"observe","maxElements":1000,"pid":123}"#, .observe(maxElements: 400, pid: 123)), + (#"{"id":1,"cmd":"scroll","dy":3}"#, .scroll(nil, dx: 0, dy: 3)), + (#"{"id":1,"cmd":"scroll","x":1,"y":2,"dx":-2}"#, .scroll(.point(CGPoint(x: 1, y: 2)), dx: -2, dy: 0)), + (#"{"id":1,"cmd":"scroll","element":5,"dy":-1}"#, .scroll(.element(5), dx: 0, dy: -1)), + (#"{"id":1,"cmd":"type","text":"hi\n"}"#, .type("hi\n")), + (#"{"id":1,"cmd":"key","keys":"cmd+q"}"#, .key(KeyCombo(keyCode: 12, modifiers: [Modifier(flag: .maskCommand, keyCode: 55)]))), + (#"{"id":1,"cmd":"drag","from":{"x":1,"y":2},"to":{"x":3,"y":4}}"#, .drag(CGPoint(x: 1, y: 2), CGPoint(x: 3, y: 4))), + (#"{"id":1,"cmd":"move","x":5.5,"y":6}"#, .move(CGPoint(x: 5.5, y: 6))), + (#"{"id":1,"cmd":"open_app","name":"Notes"}"#, .openApp(name: "Notes", bundleId: nil)), + (#"{"id":1,"cmd":"open_app","bundleId":"com.apple.Notes"}"#, .openApp(name: nil, bundleId: "com.apple.Notes")), + (#"{"id":1,"cmd":"request_permissions","accessibility":true}"#, .requestPermissions(accessibility: true, screenRecording: false)), + (#"{"id":1,"cmd":"apps","extra":null}"#, .apps), (#"{"id":1,"cmd":"frontmost"}"#, .frontmost), (#"{"id":1,"cmd":"stop"}"#, .stop), + ] + for (line, command) in good { + #expect(parsedCommand(line) == command, "\(line.prefix(60)) parses") + } + } + + @Test func invalidRequestsAreRejected() { + let codes: [(String, String)] = [ + ("not json", "bad_json"), ("[1,2]", "bad_request"), (#"{"cmd":"apps"}"#, "bad_request"), + (#"{"id":"1","cmd":"apps"}"#, "bad_request"), (#"{"id":1.5,"cmd":"apps"}"#, "bad_request"), + (#"{"id":true,"cmd":"apps"}"#, "bad_request"), (#"{"id":-1,"cmd":"apps"}"#, "bad_request"), + (#"{"id":2}"#, "bad_request"), (#"{"id":3,"cmd":"dance"}"#, "unknown_cmd"), + (#"{"id":4,"cmd":"click"}"#, "bad_request"), (#"{"id":4,"cmd":"click","x":1}"#, "bad_request"), + (#"{"id":4,"cmd":"click","x":1,"y":2,"element":3}"#, "bad_request"), + (#"{"id":4,"cmd":"click","x":1,"y":2,"button":"middle"}"#, "bad_request"), + (#"{"id":4,"cmd":"click","x":1,"y":2,"count":3}"#, "bad_request"), (#"{"id":4,"cmd":"click","x":"1","y":2}"#, "bad_request"), + (#"{"id":4,"cmd":"click","x":true,"y":2}"#, "bad_request"), (#"{"id":4,"cmd":"click","element":0}"#, "bad_request"), + (#"{"id":5,"cmd":"observe","maxElements":0}"#, "bad_request"), (#"{"id":5,"cmd":"observe","pid":-5}"#, "bad_request"), + (#"{"id":6,"cmd":"scroll"}"#, "bad_request"), (#"{"id":6,"cmd":"scroll","dy":500}"#, "bad_request"), + (#"{"id":6,"cmd":"scroll","x":1,"y":2,"element":3,"dy":1}"#, "bad_request"), (#"{"id":6,"cmd":"scroll","element":0,"dy":1}"#, "bad_request"), + (#"{"id":7,"cmd":"type","text":""}"#, "bad_request"), (#"{"id":7,"cmd":"type","text":5}"#, "bad_request"), + (#"{"id":8,"cmd":"key","keys":"cmd+nope"}"#, "bad_key"), (#"{"id":8,"cmd":"key"}"#, "bad_request"), + (#"{"id":9,"cmd":"drag","from":{"x":1},"to":{"x":3,"y":4}}"#, "bad_request"), (#"{"id":9,"cmd":"drag","from":{"x":1,"y":2}}"#, "bad_request"), + (#"{"id":10,"cmd":"open_app","name":"../Evil"}"#, "bad_request"), (#"{"id":10,"cmd":"open_app","name":"/Applications/X.app"}"#, "bad_request"), + (#"{"id":10,"cmd":"open_app","bundleId":"com apple"}"#, "bad_request"), (#"{"id":10,"cmd":"open_app"}"#, "bad_request"), + (#"{"id":10,"cmd":"open_app","name":"Notes","bundleId":"com.apple.Notes"}"#, "bad_request"), + (#"{"id":11,"cmd":"request_permissions"}"#, "bad_request"), (#"{"id":11,"cmd":"request_permissions","accessibility":1}"#, "bad_request"), + ] + for (line, code) in codes { + #expect(failureCode(line) == code, "\(line.prefix(60)) -> \(code)") + } + #expect(parseRequest(#"{"id":2}"#).id == 2, "a bad request keeps its id") + #expect(parseRequest("not json").id == nil, "unreadable JSON has no id") + let tooLong = #"{"id":12,"cmd":"type","text":""# + String(repeating: "a", count: maxTypeCharacters + 1) + #""}"# + #expect(failureCode(tooLong) == "bad_request", "type text is capped") + let huge = #"{"id":13,"cmd":"apps","pad":""# + String(repeating: "a", count: maxLineBytes) + #""}"# + #expect(failureCode(huge) == "bad_request", "request lines are capped") + #expect(isBundleIdentifier("dev.tensorfold.studio")) + for name in ["", "a b", "é.app"] { #expect(isBundleIdentifier(name) == false) } + } + + @Test func phoneRequestsStayBounded() { + let token = "12345678-1234-1234-1234-123456789ABC" + #expect(parsedCommand(#"{"id":1,"cmd":"phone_status"}"#) == .phoneStatus, "phone status parses without permission prompts") + #expect(parsedCommand(#"{"id":1,"cmd":"phone_connect","bundleId":"com.example.other"}"#) == .phoneConnect, "phone connect has a fixed native target") + let observe = "{\"id\":1,\"cmd\":\"phone_observe\",\"token\":\"\(token)\"}" + #expect(parsedCommand(observe) == .phoneObserve(token), "phone observe requires connection token") + let tap = "{\"id\":1,\"cmd\":\"phone_input\",\"token\":\"\(token)\",\"action\":\"tap\",\"x\":10,\"y\":20,\"width\":300,\"height\":600}" + #expect(parsedCommand(tap) == .phoneInput(token, .tap(CGPoint(x: 10, y: 20), CGSize(width: 300, height: 600))), "phone tap uses bounded relative coordinates") + for line in [tap.replacingOccurrences(of: "\"x\":10", with: "\"x\":300"), tap.replacingOccurrences(of: "\"x\":10", with: "\"x\":-1"), tap.replacingOccurrences(of: "\"width\":300", with: "\"width\":0"), tap.replacingOccurrences(of: "\"tap\"", with: "\"key\""), tap.replacingOccurrences(of: token, with: "wrong"), #"{"id":1,"cmd":"phone_observe"}"#] { + #expect(failureCode(line) == "bad_request", "phone invalid coordinates, token and arbitrary keys refused") + } + let size = CGSize(width: 300, height: 600) + #expect(phoneLocalPoint(CGPoint(x: 0, y: 0), size: size), "phone origin is inside") + #expect(phoneLocalPoint(CGPoint(x: 300, y: 0), size: size) == false, "phone right boundary is excluded") + #expect(phoneLocalPoint(CGPoint(x: 1, y: CGFloat.nan), size: size) == false, "phone NaN point refused") + #expect(phoneTypeAllowed("Hello\n世界\t😀"), "phone unicode and explicit line break typing supported") + #expect(phoneTypeAllowed("\u{E03D}") == false && phoneTypeAllowed("\u{1B}") == false, "phone private key codes and escape refused") + let swipe = tap.replacingOccurrences(of: #""action":"tap""#, with: #""action":"swipe","toX":15,"toY":25"#) + #expect(parsedCommand(swipe) == .phoneInput(token, .swipe(CGPoint(x: 10, y: 20), CGPoint(x: 15, y: 25), size, 0.4))) + #expect(failureCode(swipe.replacingOccurrences(of: #""toY":25"#, with: #""toY":600"#)) == "bad_request") + let typing = #"{"id":1,"cmd":"phone_input","token":"TOKEN","action":"type","text":"TEXT"}"# + .replacingOccurrences(of: "TOKEN", with: token) + #expect(parsedCommand(typing.replacingOccurrences(of: "TEXT", with: #"Hello\n世界\t😀"#)) == .phoneInput(token, .type("Hello\n世界\t😀"))) + for text in ["", #"\u001b"#, "\u{E03D}", String(repeating: "😀", count: 2001)] { + #expect(failureCode(typing.replacingOccurrences(of: "TEXT", with: text)) == "bad_request") + } + let limit = String(repeating: "😀", count: 2000) + #expect(parsedCommand(typing.replacingOccurrences(of: "TEXT", with: limit)) == .phoneInput(token, .type(limit))) + } + + @Test func repliesStayOneJSONLine() throws { + let line = encodeLine(okReply(3, ["title": "a\nb", "path": "/x"])) + let text = String(decoding: line, as: UTF8.self) + #expect(text.hasSuffix("\n") && text.filter { $0 == "\n" }.count == 1, "replies are exactly one line") + #expect(text.contains(#""path":"/x""#) && text.contains(#"\n"#), "replies escape newlines and keep slashes") + let decoded = try #require(JSONSerialization.jsonObject(with: line) as? [String: Any]) + #expect(decoded["title"] as? String == "a\nb") + #expect(decoded["path"] as? String == "/x") + #expect(decoded["id"] as? Int == 3) + #expect(decoded["ok"] as? Bool == true) + let broken = String(decoding: encodeLine(["id": 4, "ok": true, "x": Double.nan]), as: UTF8.self) + #expect(broken.contains(#""code":"internal""#) && broken.contains(#""id":4"#), "an unencodable reply becomes an internal error") + let error = errorReply(nil, HelperError("bad_json", "nope")) + #expect(error["id"] is NSNull && error["ok"] as? Bool == false && error["code"] as? String == "bad_json", "error replies carry code and null id") + } +} diff --git a/app/native/computer-use/Phone.swift b/app/native/computer-use/Phone.swift index e9e52c5a7ce..ad17e363a29 100644 --- a/app/native/computer-use/Phone.swift +++ b/app/native/computer-use/Phone.swift @@ -21,14 +21,6 @@ final class PhoneSession { } var phoneSession: PhoneSession? -func phoneLocalPoint(_ point: CGPoint, size: CGSize) -> Bool { - point.x.isFinite && point.y.isFinite && size.width.isFinite && size.height.isFinite && size.width >= 1 && size.height >= 1 && point.x >= 0 && point.y >= 0 && point.x < size.width && point.y < size.height -} -func phoneTypeAllowed(_ text: String) -> Bool { - text.unicodeScalars.allSatisfy { scalar in - scalar == "\n" || scalar == "\t" || scalar.value >= 32 && scalar.value != 127 && !(0xE000...0xF8FF).contains(scalar.value) - } -} func phoneContentRect(_ frame: CGRect) -> CGRect? { // Keep native window controls and the hidden Mac toolbar outside the image // and pointer area. These conservative insets also exclude the bezel edge. diff --git a/app/native/computer-use/SelfTest.swift b/app/native/computer-use/SelfTest.swift index c1d8c45fd39..fbabbd83bd1 100644 --- a/app/native/computer-use/SelfTest.swift +++ b/app/native/computer-use/SelfTest.swift @@ -13,110 +13,6 @@ final class Checks { } } -func failureCode(_ line: String) -> String? { - if case .failure(let error) = parseRequest(line).command { return error.code } - return nil -} - -func parsedCommand(_ line: String) -> Command? { - if case .success(let command) = parseRequest(line).command { return command } - return nil -} - -func keyChecks(_ c: Checks) { - let good: [(String, CGKeyCode, CGEventFlags)] = [ - ("cmd+shift+t", 17, [.maskCommand, .maskShift]), ("Return", 36, []), ("enter", 36, []), - ("ctrl+opt+delete", 51, [.maskControl, .maskAlternate]), ("command+alt+esc", 53, [.maskCommand, .maskAlternate]), - ("f12", 111, []), ("F1", 122, []), ("cmd+,", 43, [.maskCommand]), ("cmd+=", 24, [.maskCommand]), - ("shift+`", 50, [.maskShift]), ("pagedown", 121, []), ("pageup", 116, []), ("fn+f1", 122, [.maskSecondaryFn]), - (" cmd + a ", 0, [.maskCommand]), ("cmd+cmd+a", 0, [.maskCommand]), ("space", 49, []), ("up", 126, []), - ("down", 125, []), ("left", 123, []), ("right", 124, []), ("home", 115, []), ("end", 119, []), - ("forwarddelete", 117, []), ("backspace", 51, []), ("tab", 48, []), ("control+[", 33, [.maskControl]), - ("cmd+]", 30, [.maskCommand]), ("ctrl+;", 41, [.maskControl]), ("'", 39, []), ("/", 44, []), (".", 47, []), - ("-", 27, []), ("0", 29, []), ("9", 25, []), ("z", 6, []), ("option+shift+k", 40, [.maskAlternate, .maskShift]), - ] - for (text, code, flags) in good { - let combo = try? parseKeyCombo(text) - c.expect(combo?.keyCode == code, "key \(text) code") - c.expect(combo?.flags == flags, "key \(text) flags") - } - let order = try? parseKeyCombo("shift+cmd+t") - c.expect(order?.modifiers.map { $0.keyCode } == [56, 55], "modifiers keep their order") - c.expect((try? parseKeyCombo("cmd+cmd+a"))?.modifiers.count == 1, "a repeated modifier is pressed once") - c.expect((try? parseKeyCombo("fn+f1"))?.modifiers.first?.keyCode == nil, "fn only sets a flag") - let bad = ["", " ", "cmd", "cmd+shift", "cmd+foo", "a+b", "f13", "hyper+a", "cmd++", "+", "control+option+", String(repeating: "a", count: 100)] - for text in bad { - do { - _ = try parseKeyCombo(text) - c.expect(false, "key \(text.prefix(20)) should fail") - } catch let error as HelperError { - c.expect(error.code == "bad_key", "key \(text.prefix(20)) fails with bad_key") - } catch { - c.expect(false, "key \(text.prefix(20)) threw something else") - } - } - let printable: [(String, Bool)] = [("a", true), ("shift+a", true), ("space", true), ("cmd+a", false), ("ctrl+c", false), ("return", false), ("left", false), ("tab", false)] - for (text, expected) in printable { - c.expect((try? parseKeyCombo(text)).map(comboTypesCharacter) == expected, "\(text) types a character: \(expected)") - } -} - -func requestChecks(_ c: Checks) { - let permissions = parseRequest(#"{"id":1,"cmd":"permissions"}"#) - c.expect(permissions.id == 1, "id is read") - c.expect(parsedCommand(#"{"id":1,"cmd":"permissions"}"#) == .permissions, "permissions parses") - let codes: [(String, String)] = [ - ("not json", "bad_json"), ("[1,2]", "bad_request"), (#"{"cmd":"apps"}"#, "bad_request"), - (#"{"id":"1","cmd":"apps"}"#, "bad_request"), (#"{"id":1.5,"cmd":"apps"}"#, "bad_request"), - (#"{"id":true,"cmd":"apps"}"#, "bad_request"), (#"{"id":-1,"cmd":"apps"}"#, "bad_request"), - (#"{"id":2}"#, "bad_request"), (#"{"id":3,"cmd":"dance"}"#, "unknown_cmd"), - (#"{"id":4,"cmd":"click"}"#, "bad_request"), (#"{"id":4,"cmd":"click","x":1}"#, "bad_request"), - (#"{"id":4,"cmd":"click","x":1,"y":2,"element":3}"#, "bad_request"), - (#"{"id":4,"cmd":"click","x":1,"y":2,"button":"middle"}"#, "bad_request"), - (#"{"id":4,"cmd":"click","x":1,"y":2,"count":3}"#, "bad_request"), (#"{"id":4,"cmd":"click","x":"1","y":2}"#, "bad_request"), - (#"{"id":4,"cmd":"click","x":true,"y":2}"#, "bad_request"), (#"{"id":4,"cmd":"click","element":0}"#, "bad_request"), - (#"{"id":5,"cmd":"observe","maxElements":0}"#, "bad_request"), (#"{"id":5,"cmd":"observe","pid":-5}"#, "bad_request"), - (#"{"id":6,"cmd":"scroll"}"#, "bad_request"), (#"{"id":6,"cmd":"scroll","dy":500}"#, "bad_request"), - (#"{"id":6,"cmd":"scroll","x":1,"y":2,"element":3,"dy":1}"#, "bad_request"), (#"{"id":6,"cmd":"scroll","element":0,"dy":1}"#, "bad_request"), - (#"{"id":7,"cmd":"type","text":""}"#, "bad_request"), (#"{"id":7,"cmd":"type","text":5}"#, "bad_request"), - (#"{"id":8,"cmd":"key","keys":"cmd+nope"}"#, "bad_key"), (#"{"id":8,"cmd":"key"}"#, "bad_request"), - (#"{"id":9,"cmd":"drag","from":{"x":1},"to":{"x":3,"y":4}}"#, "bad_request"), (#"{"id":9,"cmd":"drag","from":{"x":1,"y":2}}"#, "bad_request"), - (#"{"id":10,"cmd":"open_app","name":"../Evil"}"#, "bad_request"), (#"{"id":10,"cmd":"open_app","name":"/Applications/X.app"}"#, "bad_request"), - (#"{"id":10,"cmd":"open_app","bundleId":"com apple"}"#, "bad_request"), (#"{"id":10,"cmd":"open_app"}"#, "bad_request"), - (#"{"id":10,"cmd":"open_app","name":"Notes","bundleId":"com.apple.Notes"}"#, "bad_request"), - (#"{"id":11,"cmd":"request_permissions"}"#, "bad_request"), (#"{"id":11,"cmd":"request_permissions","accessibility":1}"#, "bad_request"), - ] - for (line, code) in codes { - c.expect(failureCode(line) == code, "\(line.prefix(60)) -> \(code)") - } - c.expect(parseRequest(#"{"id":2}"#).id == 2, "a bad request keeps its id") - c.expect(parseRequest("not json").id == nil, "unreadable JSON has no id") - let tooLong = #"{"id":12,"cmd":"type","text":""# + String(repeating: "a", count: maxTypeCharacters + 1) + #""}"# - c.expect(failureCode(tooLong) == "bad_request", "type text is capped") - let huge = #"{"id":13,"cmd":"apps","pad":""# + String(repeating: "a", count: maxLineBytes) + #""}"# - c.expect(failureCode(huge) == "bad_request", "request lines are capped") - let good: [(String, Command)] = [ - (#"{"id":1,"cmd":"click","x":10,"y":20}"#, .click(.point(CGPoint(x: 10, y: 20)), .left, 1)), - (#"{"id":1,"cmd":"click","element":4,"button":"right","count":2}"#, .click(.element(4), .right, 2)), - (#"{"id":1,"cmd":"observe"}"#, .observe(maxElements: 150, pid: nil)), - (#"{"id":1,"cmd":"observe","maxElements":1000,"pid":123}"#, .observe(maxElements: 400, pid: 123)), - (#"{"id":1,"cmd":"scroll","dy":3}"#, .scroll(nil, dx: 0, dy: 3)), - (#"{"id":1,"cmd":"scroll","x":1,"y":2,"dx":-2}"#, .scroll(.point(CGPoint(x: 1, y: 2)), dx: -2, dy: 0)), - (#"{"id":1,"cmd":"scroll","element":5,"dy":-1}"#, .scroll(.element(5), dx: 0, dy: -1)), - (#"{"id":1,"cmd":"type","text":"hi\n"}"#, .type("hi\n")), - (#"{"id":1,"cmd":"key","keys":"cmd+q"}"#, .key(KeyCombo(keyCode: 12, modifiers: [Modifier(flag: .maskCommand, keyCode: 55)]))), - (#"{"id":1,"cmd":"drag","from":{"x":1,"y":2},"to":{"x":3,"y":4}}"#, .drag(CGPoint(x: 1, y: 2), CGPoint(x: 3, y: 4))), - (#"{"id":1,"cmd":"move","x":5.5,"y":6}"#, .move(CGPoint(x: 5.5, y: 6))), - (#"{"id":1,"cmd":"open_app","name":"Notes"}"#, .openApp(name: "Notes", bundleId: nil)), - (#"{"id":1,"cmd":"open_app","bundleId":"com.apple.Notes"}"#, .openApp(name: nil, bundleId: "com.apple.Notes")), - (#"{"id":1,"cmd":"request_permissions","accessibility":true}"#, .requestPermissions(accessibility: true, screenRecording: false)), - (#"{"id":1,"cmd":"apps","extra":null}"#, .apps), (#"{"id":1,"cmd":"frontmost"}"#, .frontmost), (#"{"id":1,"cmd":"stop"}"#, .stop), - ] - for (line, command) in good { - c.expect(parsedCommand(line) == command, "\(line.prefix(60)) parses") - } -} - func pointChecks(_ c: Checks) { let displays = [CGRect(x: 0, y: 0, width: 1512, height: 982), CGRect(x: 1512, y: -200, width: 2560, height: 1440)] let cases: [(CGPoint, Bool)] = [ @@ -188,7 +84,6 @@ func miscChecks(_ c: Checks) { c.expect(isOwnBundle(bundle, own: own) == expected, "own bundle \(bundle ?? "nil"): \(expected)") } c.expect(!isOwnBundle("com.apple.Notes", own: ""), "an empty own id matches nothing") - c.expect(isBundleIdentifier(own) && !isBundleIdentifier("") && !isBundleIdentifier("a b") && !isBundleIdentifier("é.app"), "bundle id syntax") c.expect(scrollSteps(dx: 0, dy: 3) == [WheelStep(vertical: -3, horizontal: 0)], "dy down is a negative wheel") c.expect(scrollSteps(dx: 0, dy: 25).map { $0.vertical } == [-10, -10, -5], "long scrolls split into steps") c.expect(scrollSteps(dx: -4, dy: 0) == [WheelStep(vertical: 0, horizontal: 4)], "dx left is a positive wheel") @@ -198,37 +93,15 @@ func miscChecks(_ c: Checks) { let path = dragPath(from: from, to: to) c.expect(path.last == to && path.first != from && (8...60).contains(path.count), "drag path ends on the target") c.expect(dragPath(from: from, to: from).count == 8, "a zero drag still moves in steps") - let line = encodeLine(okReply(3, ["title": "a\nb", "path": "/x"])) - let text = String(decoding: line, as: UTF8.self) - c.expect(text.hasSuffix("\n") && text.filter { $0 == "\n" }.count == 1, "replies are exactly one line") - c.expect(text.contains(#""path":"/x""#) && text.contains(#"\n"#), "replies escape newlines and keep slashes") - let broken = String(decoding: encodeLine(["id": 4, "ok": true, "x": Double.nan]), as: UTF8.self) - c.expect(broken.contains(#""code":"internal""#) && broken.contains(#""id":4"#), "an unencodable reply becomes an internal error") - let error = errorReply(nil, HelperError("bad_json", "nope")) - c.expect(error["id"] is NSNull && error["ok"] as? Bool == false && error["code"] as? String == "bad_json", "error replies carry code and null id") } func phoneChecks(_ c: Checks) { let token = "12345678-1234-1234-1234-123456789ABC" - c.expect(parsedCommand(#"{"id":1,"cmd":"phone_status"}"#) == .phoneStatus, "phone status parses without permission prompts") - c.expect(parsedCommand(#"{"id":1,"cmd":"phone_connect","bundleId":"com.example.other"}"#) == .phoneConnect, "phone connect has a fixed native target") - let observe = "{\"id\":1,\"cmd\":\"phone_observe\",\"token\":\"\(token)\"}" - c.expect(parsedCommand(observe) == .phoneObserve(token), "phone observe requires connection token") - let tap = "{\"id\":1,\"cmd\":\"phone_input\",\"token\":\"\(token)\",\"action\":\"tap\",\"x\":10,\"y\":20,\"width\":300,\"height\":600}" - c.expect(parsedCommand(tap) == .phoneInput(token, .tap(CGPoint(x: 10, y: 20), CGSize(width: 300, height: 600))), "phone tap uses bounded relative coordinates") - for line in [tap.replacingOccurrences(of: "\"x\":10", with: "\"x\":300"), tap.replacingOccurrences(of: "\"x\":10", with: "\"x\":-1"), tap.replacingOccurrences(of: "\"width\":300", with: "\"width\":0"), tap.replacingOccurrences(of: "\"tap\"", with: "\"key\""), tap.replacingOccurrences(of: token, with: "wrong"), #"{"id":1,"cmd":"phone_observe"}"#] { - c.expect(failureCode(line) == "bad_request", "phone invalid coordinates, token and arbitrary keys refused") - } let size = CGSize(width: 300, height: 600) - c.expect(phoneLocalPoint(CGPoint(x: 0, y: 0), size: size), "phone origin is inside") - c.expect(!phoneLocalPoint(CGPoint(x: 300, y: 0), size: size), "phone right boundary is excluded") - c.expect(!phoneLocalPoint(CGPoint(x: 1, y: CGFloat.nan), size: size), "phone NaN point refused") c.expect(phoneContentRect(CGRect(x: 100, y: 200, width: 320, height: 700)) == CGRect(x: 110, y: 248, width: 300, height: 642), "phone image and input exclude window controls") c.expect(phoneContentRect(CGRect(x: 0, y: 0, width: 50, height: 50)) == nil, "phone cannot target tiny toolbar windows") let global = try? phoneGlobalPoint(CGPoint(x: 150, y: 300), size: size, frame: CGRect(x: 100, y: 200, width: 320, height: 700)) c.expect(global == CGPoint(x: 260, y: 569), "phone coordinates map only into clipped window content") - c.expect(phoneTypeAllowed("Hello\n世界\t😀"), "phone unicode and explicit line break typing supported") - c.expect(!phoneTypeAllowed("\u{E03D}") && !phoneTypeAllowed("\u{1B}"), "phone private key codes and escape refused") c.expect(phoneProtectedText("Enter your passcode") && phoneProtectedText("iPhone in use") && phoneProtectedText("Apple Account password"), "phone lock, authentication and disconnected states are refused") c.expect(!phoneProtectedText("Synthetic sample home screen"), "ordinary phone screen text accepted") let windowBounds: [String: Any] = ["X": 0, "Y": 0, "Width": 300, "Height": 600] @@ -261,8 +134,6 @@ func attachmentTextChecks(_ c: Checks) { func runSelfTest() -> Int32 { let checks = Checks() - keyChecks(checks) - requestChecks(checks) pointChecks(checks) filterChecks(checks) textChecks(checks) diff --git a/app/scripts/build-computer-helper.mjs b/app/scripts/build-computer-helper.mjs index bea93580f12..55f58313c9b 100644 --- a/app/scripts/build-computer-helper.mjs +++ b/app/scripts/build-computer-helper.mjs @@ -1,5 +1,5 @@ #!/usr/bin/env node -// Compiles native/computer-use/*.swift into build/computer-use/tensorfold-computer, then runs its --self-test. +// Compiles the Mac helper and shared ComputerUseChecks sources, excluding package tests and build artifacts. // A stamp beside the binary records the source digest and the binary's own sha256; swiftc is skipped only // when both still match. Sources go to swiftc by relative name so no local build path lands in the binary. import { createHash } from 'node:crypto' @@ -29,7 +29,13 @@ export function swiftcArgs(sourceNames, output) { } export async function readSources(sourceDir) { - const names = (await readdir(sourceDir)).filter((name) => name.endsWith('.swift')).sort() + const names = [] + for (const dir of ['.', 'ComputerUseChecks/Sources/ComputerUseChecks']) { + for (const name of await readdir(path.join(sourceDir, dir))) { + if (name.endsWith('.swift')) names.push(path.posix.join(dir, name)) + } + } + names.sort() if (!names.length) throw new Error(`No Swift sources in ${sourceDir}.`) return Promise.all(names.map(async (name) => ({ name, bytes: await readFile(path.join(sourceDir, name)) }))) } diff --git a/app/scripts/build-computer-helper.test.mjs b/app/scripts/build-computer-helper.test.mjs index 6b019c1711d..e04841d1892 100644 --- a/app/scripts/build-computer-helper.test.mjs +++ b/app/scripts/build-computer-helper.test.mjs @@ -37,6 +37,16 @@ async function main() { await writeFile(path.join(paths.sourceDir, 'main.swift'), 'print("hi")\n') await writeFile(path.join(paths.sourceDir, 'Keys.swift'), 'let a = 1\n') await writeFile(path.join(paths.sourceDir, 'README.txt'), 'not a source\n') + const checks = path.join(paths.sourceDir, 'ComputerUseChecks') + const shared = path.join(checks, 'Sources', 'ComputerUseChecks') + await mkdir(shared, { recursive: true }) + await mkdir(path.join(checks, 'Tests', 'ComputerUseChecksTests'), { recursive: true }) + await mkdir(path.join(checks, '.build'), { recursive: true }) + await writeFile(path.join(shared, 'Protocol.swift'), 'let request = 1\n') + await writeFile(path.join(shared, 'Platform.swift'), 'let platform = 1\n') + await writeFile(path.join(checks, 'Package.swift'), '// package manifest, not helper source\n') + await writeFile(path.join(checks, 'Tests', 'ComputerUseChecksTests', 'ProtocolTests.swift'), '#error("tests must not ship")\n') + await writeFile(path.join(checks, '.build', 'Generated.swift'), '#error("build artifacts must not ship")\n') assert.deepEqual(swiftcArgs(['a.swift'], 'out').slice(0, 9), ['swiftc', '-O', '-swift-version', '5', '-module-name', 'TensorFoldComputer', '-target', 'arm64-apple-macos13.0', '-framework']) assert.equal(parseSelfTest('{"ok":true,"checks":12}\n'), 12) @@ -59,7 +69,11 @@ async function main() { assert.equal(first.compiles(), 1) const compile = first.calls.find((call) => call.args[0] === 'swiftc') assert.equal(compile.cwd, paths.sourceDir) - assert.deepEqual(compile.args.slice(-2), ['Keys.swift', 'main.swift'], 'sources go by sorted relative name') + assert.deepEqual(compile.args.slice(-4), [ + 'ComputerUseChecks/Sources/ComputerUseChecks/Platform.swift', + 'ComputerUseChecks/Sources/ComputerUseChecks/Protocol.swift', + 'Keys.swift', 'main.swift', + ], 'shared sources compile by relative name, without the package manifest, tests or artifacts') assert.ok(!compile.args.some((arg) => arg.endsWith('README.txt'))) assert.equal(await readFile(paths.binary, 'utf8'), 'fake helper binary') assert.equal((await stat(paths.binary)).mode & 0o777, 0o755) @@ -74,6 +88,13 @@ async function main() { assert.equal(second.calls.filter((call) => call.command === 'xcrun').length, 0) assert.equal(second.calls.filter((call) => call.args[0] === '--self-test').length, 1) + await writeFile(path.join(shared, 'Protocol.swift'), 'let request = 2\n') + const sharedEdit = toolchain() + assert.equal((await build({ root, run: sharedEdit.run, log: () => {} })).compiled, true, 'shared parser edits invalidate the cache') + await writeFile(path.join(checks, 'Tests', 'ComputerUseChecksTests', 'ProtocolTests.swift'), '#error("edited test must not ship")\n') + const testEdit = toolchain() + assert.equal((await build({ root, run: testEdit.run, log: () => {} })).compiled, false, 'test-only edits do not change the helper') + // An edited source, a new source, a replaced binary and --force each rebuild. await writeFile(path.join(paths.sourceDir, 'Keys.swift'), 'let a = 2\n') const edited = toolchain() @@ -104,7 +125,7 @@ async function main() { await assert.rejects(() => buildComputerHelper({ root, run: toolchain().run, platform: 'linux', log: () => {} }), /only on macOS/) await rm(paths.sourceDir, { recursive: true, force: true }) - await mkdir(paths.sourceDir) + await mkdir(shared, { recursive: true }) await assert.rejects(() => build({ root, run: toolchain().run, log: () => {} }), /No Swift sources/) } finally { await rm(root, { recursive: true, force: true }) diff --git a/app/scripts/computer-request-parser.test.mjs b/app/scripts/computer-request-parser.test.mjs new file mode 100644 index 00000000000..02b6e2ad560 --- /dev/null +++ b/app/scripts/computer-request-parser.test.mjs @@ -0,0 +1,68 @@ +import assert from 'node:assert/strict' +import { spawnSync } from 'node:child_process' +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' + +const native = fileURLToPath(new URL('../native/computer-use/', import.meta.url)) +const shared = path.join(native, 'ComputerUseChecks', 'Sources', 'ComputerUseChecks') +const packaged = existsSync(path.join(shared, 'Protocol.swift')) +const compiler = spawnSync('swiftc', ['--version'], { encoding: 'utf8', timeout: 10_000 }) +if (compiler.status !== 0 || !packaged && process.platform !== 'darwin') { + console.log('computer parser checks skipped: Swift and a supported production source layout are required') +} else { + const root = mkdtempSync(path.join(os.tmpdir(), 'tf-parser-bounds-')) + try { + const names = packaged ? readdirSync(shared).filter((name) => name.endsWith('.swift')).sort() : ['Keys.swift', 'Protocol.swift'] + for (const name of names) writeFileSync(path.join(root, name), readFileSync(path.join(packaged ? shared : native, name))) + if (!packaged) { + const phone = readFileSync(path.join(native, 'Phone.swift'), 'utf8') + const start = phone.indexOf('func phoneLocalPoint('), end = phone.indexOf('func phoneContentRect(') + assert.ok(start >= 0 && end > start, 'compile the production phone validators verbatim') + writeFileSync(path.join(root, 'PhoneValidation.swift'), `import Foundation\n${phone.slice(start, end)}`) + names.push('PhoneValidation.swift') + } + writeFileSync(path.join(root, 'main.swift'), `import Foundation +while let line = readLine() { + let parsed = parseRequest(line) + switch parsed.command { + case .failure(let error): + FileHandle.standardOutput.write(encodeLine(errorReply(parsed.id, error))) + case .success(.scroll(_, let dx, let dy)): + FileHandle.standardOutput.write(encodeLine(okReply(parsed.id ?? 0, ["dx": dx, "dy": dy]))) + case .success: + fatalError("Probe accepts scroll requests only") + } +} +`) + const build = spawnSync('swiftc', ['-O', '-swift-version', '5', '-o', 'parser-probe', ...names, 'main.swift'], { cwd: root, encoding: 'utf8', timeout: 90_000, maxBuffer: 1024 * 1024 }) + assert.equal(build.status, 0, `production parser must compile: ${build.stderr}`) + const parse = (delta) => { + const result = spawnSync(path.join(root, 'parser-probe'), [], { cwd: root, input: `${JSON.stringify({ id: 7, cmd: 'scroll', ...delta })}\n`, encoding: 'utf8', timeout: 5_000, maxBuffer: 1024 * 1024 }) + assert.equal(result.status, 0, `parser must reject ${JSON.stringify(delta)} without terminating (${result.signal ?? result.error?.code ?? result.status})`) + const lines = result.stdout.trim().split('\n') + assert.equal(lines.length, 1, 'one request produces one JSON-line reply') + return JSON.parse(lines[0]) + } + for (const axis of ['dx', 'dy']) { + for (const value of [1e100, -1e100, 1e308, -1e308, -9223372036854775808, 201, -201, 200.5, -200.5, true, '3']) { + const reply = parse({ [axis]: value }) + assert.equal(reply.id, 7) + assert.equal(reply.ok, false) + assert.equal(reply.code, 'bad_request') + assert.ok(typeof reply.error === 'string' && reply.error.length > 0) + } + } + for (const [input, expected] of [ + [{ dx: 200, dy: -200 }, { dx: 200, dy: -200 }], + [{ dx: 200.49, dy: -200.49 }, { dx: 200, dy: -200 }], + [{ dx: -0.5, dy: 0.5 }, { dx: -1, dy: 1 }], + [{ dy: 3 }, { dx: 0, dy: 3 }], + ]) assert.deepEqual(parse(input), { id: 7, ok: true, ...expected }) + for (const input of [{}, { dx: 0, dy: 0 }, { dx: 0.49, dy: -0.49 }]) assert.equal(parse(input).code, 'bad_request') + console.log('Production Swift parser rejects oversized scroll values without crashing and preserves limits, rounding and JSON-line replies') + } finally { + rmSync(root, { recursive: true, force: true }) + } +} diff --git a/app/shared/bot-policy.ts b/app/shared/bot-policy.ts index 99b106976b2..132b74f469b 100644 --- a/app/shared/bot-policy.ts +++ b/app/shared/bot-policy.ts @@ -1,6 +1,7 @@ import type { AgentPreset, ApprovalMode, BotThreadConfig, Provider, Thread } from '../electron/agent/types' import { isExternalProvider } from './provider-trust' import { normalizeBotToolScope } from './bot-tool-policy' +import { normalizeBotReasoningEffort } from './bot-reasoning' const lanes = new Set(['planning', 'development', 'review', 'research', 'operations']) const apiTransports = new Set([undefined, 'chat-completions']) @@ -21,6 +22,9 @@ export function normalizeAgentPresets(value: unknown, strict = false): AgentPres for (const item of value.slice(0, 200)) { if (!item || typeof item !== 'object' || Array.isArray(item)) { if (strict) throw new Error('Invalid bot.'); continue } const raw = item as Record + let reasoningEffort + try { reasoningEffort = normalizeBotReasoningEffort(raw.reasoningEffort) } + catch (error) { if (strict) throw error; continue } let toolScope, toolScopeProblem try { toolScope = normalizeBotToolScope(raw.toolScope) @@ -50,6 +54,7 @@ export function normalizeAgentPresets(value: unknown, strict = false): AgentPres id: preset.id, name: preset.name.slice(0, 80), role: preset.role.slice(0, 240), lane: preset.lane, providerId: preset.providerId.slice(0, 200), providerAccountId: preset.providerAccountId?.slice(0, 200) ?? null, model: preset.model.slice(0, 300), instructions: preset.instructions?.slice(0, 16_000) ?? '', + ...(reasoningEffort !== undefined ? { reasoningEffort } : {}), approvalScope: preset.approvalScope ?? 'readonly', executionTarget: preset.executionTarget ?? 'workspace', ...(toolScope ? { toolScope } : {}), ...(toolScopeProblem ? { toolScopeProblem } : {}), @@ -70,6 +75,7 @@ export function captureBotConfig(preset: AgentPreset, providers: Provider[], now const snapshot: BotThreadConfig = { presetId: normalized.id, name: normalized.name.trim(), role: normalized.role, instructions: normalized.instructions ?? '', providerId: normalized.providerId, providerAccountId: normalized.providerAccountId ?? null, model: normalized.model, + ...(normalized.reasoningEffort !== undefined ? { reasoningEffort: normalized.reasoningEffort } : {}), approvalScope: normalized.approvalScope ?? 'readonly', executionTarget: normalized.executionTarget ?? 'workspace', capturedAt: now, ...(normalized.toolScope ? { toolScope: normalizeBotToolScope(normalized.toolScope) } : {}), } @@ -95,6 +101,7 @@ export function botRunApprovalMode(thread: Pick, presets: AgentPr if (!bot || typeof bot !== 'object' || Array.isArray(bot)) throw new Error('This chat has an invalid captured bot configuration; start a new bot chat.') if (bot.toolScopeProblem !== undefined) throw new Error('This chat\'s captured tool selection needs repair; start a new chat from the repaired bot.') normalizeBotToolScope(bot.toolScope) + normalizeBotReasoningEffort(bot.reasoningEffort) if (typeof bot.presetId !== 'string' || !/^[a-zA-Z0-9_-]{1,100}$/.test(bot.presetId) || typeof bot.name !== 'string' || !bot.name.trim() || bot.name.length > 80 || typeof bot.instructions !== 'string' || bot.instructions.length > 16_000 || typeof bot.role !== 'string' || bot.role.length > 240 || typeof bot.providerId !== 'string' || typeof bot.model !== 'string' || (bot.providerAccountId !== null && typeof bot.providerAccountId !== 'string')) throw new Error('This chat has an invalid bot configuration.') const current = presets.find((preset) => preset.id === bot.presetId) if (!current || current.archivedAt) throw new Error('This bot is archived; restore it before continuing its chat.') diff --git a/app/shared/bot-reasoning.ts b/app/shared/bot-reasoning.ts new file mode 100644 index 00000000000..ac8e5c8bf1e --- /dev/null +++ b/app/shared/bot-reasoning.ts @@ -0,0 +1,17 @@ +import type { ReasoningEffortSetting, Thread } from '../electron/agent/types' + +const efforts = new Set([ + 'none', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultrathink', 'ultracode', 'dynamic', '512', +]) + +export function normalizeBotReasoningEffort(value: unknown): ReasoningEffortSetting | undefined { + if (value === undefined) return undefined + if (typeof value !== 'string' || !efforts.has(value as ReasoningEffortSetting)) { + throw new Error('Invalid bot reasoning effort; choose an available effort level.') + } + return value as ReasoningEffortSetting +} + +export function botRunReasoningEffort(thread: Pick, fallback: ReasoningEffortSetting): ReasoningEffortSetting { + return normalizeBotReasoningEffort(thread.bot?.reasoningEffort) ?? fallback +} diff --git a/app/src/components/Board.ticket-details.test.tsx b/app/src/components/Board.ticket-details.test.tsx new file mode 100644 index 00000000000..0460d449014 --- /dev/null +++ b/app/src/components/Board.ticket-details.test.tsx @@ -0,0 +1,51 @@ +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import path from 'node:path' +import React from 'react' +import ts from 'typescript' +import { fixtureText, reviewedLanguageImport } from './preferences/language-test-fixture' + +const TicketDetailsButton = () => null, TicketArchiveButton = () => null +const opened: string[] = [] +const ticket: any = { id: 'ticket', projectId: 'project', title: 'Full details', body: 'Untruncated text', type: 'task', priority: 'medium', effort: 'small', status: 'in_progress', tags: [], threadId: 'chat', order: 0 } +const state: any = { tickets: [ticket], rooms: [], projects: [{ id: 'project', name: 'Synthetic' }], settings: { providers: [] }, openThread: (id: string) => opened.push(id) } +const useStore = Object.assign((select: (value: any) => unknown) => select(state), { getState: () => state }) +const jsx = { jsx: (type: any, props: any) => React.createElement(type, props), jsxs: (type: any, props: any) => React.createElement(type, props), Fragment: React.Fragment } +const imports: Record = { + react: { useState: (initial: unknown) => [typeof initial === 'function' ? initial() : initial, () => {}], useEffect() {}, useMemo: (make: () => unknown) => make() }, + 'react/jsx-runtime': jsx, + clsx: (...values: unknown[]) => values.filter(Boolean).join(' '), + '../lib/preferences/useAuthoredText': { useAuthoredText: () => fixtureText }, + '../lib/preferences/language-packs': { authoredText: (_locale: string, value: string) => fixtureText(value) }, + '../lib/store': { useStore }, + '../lib/icons': { Icon: () => null }, + './ui': { Button: () => null, Menu: () => null, MenuItem: () => null }, + '../lib/policy': { allowedProviders: () => [], projectDefaultModel: () => ({}) }, + '../lib/provider-accounts': { modelDisplayName: (_provider: unknown, value: string) => value, providerModelGroups: () => [] }, + '../../shared/ticket-dependencies': { resolveTicketDependencies: () => ({ state: 'ready' }) }, + './board/TicketDetails': { TicketDetailsButton, TicketArchiveButton }, +} +const loaded = { exports: {} as any } +const output = ts.transpileModule(readFileSync(path.join(__dirname, 'Board.tsx'), 'utf8') + '\nexports.Card = Card;', { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, esModuleInterop: true }, +}).outputText +new Function('require', 'module', 'exports', output)((id: string) => { + const reviewed = reviewedLanguageImport(id, imports) + if (reviewed.matched) return reviewed.value + assert.ok(id in imports, `Reviewed Board import ${id}`) + return imports[id] +}, loaded, loaded.exports) + +function find(node: any, type: unknown): any[] { + if (!node || typeof node !== 'object') return [] + return [...(node.type === type ? [node] : []), ...React.Children.toArray(node.props?.children).flatMap((child) => find(child, type))] +} +const card = loaded.exports.Card({ t: ticket, rooms: [], allTickets: [ticket], onDragStart() {}, onRun() {}, onSetMode() {} }) +assert.equal(find(card, TicketDetailsButton).length, 1, 'every card needs an explicit entry point to its full editable details') +assert.equal(find(card, TicketDetailsButton)[0].props.ticket, ticket) +card.props.onClick() +assert.deepEqual(opened, ['chat'], 'existing card navigation to the worker chat remains available') +const board = loaded.exports.Board({ projectId: 'project' }) +assert.equal(find(board, TicketArchiveButton).length, 1, 'the board needs a visible archive entry point') +assert.equal(find(board, TicketArchiveButton)[0].props.projectId, 'project') +console.log('Kanban cards expose details, the board exposes archives, and existing worker-chat navigation is preserved') diff --git a/app/src/components/Board.tsx b/app/src/components/Board.tsx index 7c94b8d2cf7..e7a7599a3d0 100644 --- a/app/src/components/Board.tsx +++ b/app/src/components/Board.tsx @@ -10,6 +10,7 @@ import { allowedProviders, projectDefaultModel } from '../lib/policy' import { modelDisplayName, providerModelGroups } from '../lib/provider-accounts' import type { KanbanPhaseModel, Project, ProjectKanbanSettings, Provider, Room, Ticket, TicketExecutionMode, TicketStatus, TicketWorkOptions } from '../lib/types' import { resolveTicketDependencies } from '../../shared/ticket-dependencies' +import { TicketDetailsButton, TicketArchiveButton } from './board/TicketDetails' const EXEC_MODES: { id: TicketExecutionMode; label: string; icon: IconName; desc: string }[] = [ { id: 'solo', get label() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "Solo") }, icon: 'cpu', get desc() { return authoredText(useLocaleStore.getState().settings?.uiPreferences?.locale, "One agent on the configured model") } }, @@ -229,7 +230,8 @@ function Card({ className={clsx('group mb-2 rounded-xl border border-line bg-card p-3 shadow-card transition-colors hover:border-line-strong', t.threadId ? 'cursor-pointer' : activeRun ? 'cursor-default' : 'cursor-grab active:cursor-grabbing')} >
-
{t.title}
+
{t.title}
+
{t.body &&

{t.body}

} @@ -452,6 +454,7 @@ export function Board({ projectId }: { projectId: string }) {
+
{modelMode === 'single' ? tx("One model · {value0}", { value0: selectionLabel(singleModel, modelProviders) }) : tx("Phased models · Draft, ticket review, build, work review, final gate")}
diff --git a/app/src/components/Bots.tsx b/app/src/components/Bots.tsx index 85797d8312d..8118a547694 100644 --- a/app/src/components/Bots.tsx +++ b/app/src/components/Bots.tsx @@ -18,6 +18,7 @@ import { BotVmControls } from './bots/BotVmControls' import { BotRecipes } from './bots/BotRecipes' import { BotToolScopeEditor } from './bots/BotToolScopeEditor' import { BotRoutineSetup } from './bots/BotRoutineSetup' +import { BotReasoningEffort, effortForBotModel } from './bots/BotReasoningEffort' import { inspectBotToolScope } from '../../shared/bot-tool-policy' const EMPTY_BOTS: AgentPreset[] = [] @@ -64,7 +65,7 @@ export function Bots() { const first = models[0] const now = Date.now() setError(null) - setDraft({ id: `bot_${crypto.randomUUID()}`, name: template.name, role: template.role, instructions: template.instructions, lane: template.lane, providerId: first?.provider.id ?? '', providerAccountId: first?.group.accountId ?? null, model: first?.group.models[0] ?? '', approvalScope: 'readonly', executionTarget: 'workspace', paused: false, archivedAt: null, createdAt: now, updatedAt: now }) + setDraft({ id: `bot_${crypto.randomUUID()}`, name: template.name, role: template.role, instructions: template.instructions, lane: template.lane, providerId: first?.provider.id ?? '', providerAccountId: first?.group.accountId ?? null, model: first?.group.models[0] ?? '', reasoningEffort: effortForBotModel(settings?.reasoningEffort ?? 'medium', first?.provider, first?.group.models[0]), approvalScope: 'readonly', executionTarget: 'workspace', paused: false, archivedAt: null, createdAt: now, updatedAt: now }) } const saveBot = async (bot: AgentPreset) => { setBusyId(bot.id); setError(null) @@ -105,10 +106,11 @@ export function Bots() {