Merge origin/main into Claude parent environment isolation

This commit is contained in:
Brennan Benson
2026-11-09 02:39:11 -08:00
156 changed files with 1349 additions and 8249 deletions
@@ -1,23 +0,0 @@
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { test } from 'node:test'
const here = new URL('./', import.meta.url)
const action = readFileSync(new URL('action.yml', here), 'utf8')
test('is a node24 JavaScript action with an always-run post step', () => {
// A composite action has no `post:`, so the lease could never be released on cancel or failure.
assert.match(action, /^ {2}using: node24$/m)
assert.doesNotMatch(action, /using: composite/)
assert.match(action, /^ {2}main: main\.mjs$/m)
assert.match(action, /^ {2}post: post\.mjs$/m)
assert.match(action, /^ {2}post-if: always\(\)$/m)
})
test('declares the inputs the wave-chain callers depend on', () => {
for (const input of ['bucket:', 'object:', 'holder-key:', 'release:']) {
assert.match(action, new RegExp(`^ {2}${input}$`, 'm'), input)
}
assert.match(action, /default: \$\{\{ github\.repository \}\}\/\$\{\{ github\.run_id \}\}/)
assert.match(action, /default: 'true'/)
})
@@ -234,18 +234,6 @@ test('fails closed when the bucket answers 5xx', async () => {
assert.equal(storage.state.requests.filter((request) => request.method !== 'GET').length, 0)
})
test('fails closed when permission is denied', async () => {
const storage = fakeStorage({
faults: [{ when: (request) => request.method === 'GET', status: 403 }]
})
const error = await leaseFor(storage)
.acquire(HOLDER)
.catch((thrown) => thrown)
assert.match(error.message, /lease inspection failed: 403/)
})
test('treats an unreadable record as held, not free', async () => {
const storage = fakeStorage({
object: { generation: '1500', body: { holder_key: 'stablyai/orca/9001' } }
+133
View File
@@ -0,0 +1,133 @@
name: Server-only Linux artifact
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
paths:
- 'config/scripts/orcad-distribution/server-artifact/**'
- '.github/workflows/orca-server-artifact.yml'
# The launcher relies on how the CLI picks and starts its serve runtime.
- 'src/cli/runtime/launch.ts'
- 'src/cli/runtime/orca-app-executable.ts'
- 'src/cli/runtime/serve-orcad-launch.ts'
- 'src/shared/orcad-local-serve-selection.ts'
- 'src/shared/orcad-artifacts.ts'
# Catch serve regressions on main between releases.
schedule:
- cron: '45 11 * * *'
workflow_dispatch:
# Releases pass the qualified template this run already built, so the tarball ships its exact bytes.
workflow_call:
inputs:
ref:
description: Git ref to check out, e.g. the release tag
type: string
required: true
template_artifact:
description: Name of this run's qualified orcad-template artifact; blank builds the host slot
type: string
default: ''
outputs:
packed:
description: "'true' when both tarballs were packed and passed the smoke"
value: ${{ jobs.package.outputs.packed }}
permissions:
contents: read
concurrency:
group: orca-server-artifact-${{ inputs.ref && format('run-{0}', github.run_id) || github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ !inputs.ref }}
jobs:
package:
if: github.event_name != 'pull_request' || github.event.pull_request.draft != true
strategy:
fail-fast: false
matrix:
include:
- arch: x64
runner: ubuntu-24.04
- arch: arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 30
permissions:
contents: read
actions: read
env:
ORCA_BACKGROUND_LAUNCH: '1'
TARGET: linux-${{ matrix.arch }}-glibc
outputs:
packed: ${{ steps.smoke.outcome == 'success' }}
steps:
- uses: actions/checkout@v6
with:
ref: ${{ inputs.ref }}
persist-credentials: false
# A release cut from a ref older than this workflow has nothing to pack; skip instead of failing.
- name: Check the ref can pack the tarball
id: supported
run: |
if [ -f config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs ]; then
echo 'supported=true' >> "$GITHUB_OUTPUT"
else
echo '::notice::This ref predates the server-only tarball; skipping it.'
fi
- uses: ./.github/actions/install-node-dependencies
if: steps.supported.outputs.supported == 'true'
with:
cache-pnpm-store: ${{ !inputs.ref }}
- name: Use the qualified release template
if: steps.supported.outputs.supported == 'true' && inputs.template_artifact != ''
uses: actions/download-artifact@v8
with:
name: ${{ inputs.template_artifact }}
path: out/orcad-template
# Without a release template, build this runner's slot the way the desktop template does.
- uses: ./.github/actions/build-mobile-web-bundle
if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == ''
- name: Build this runner's template slot
if: steps.supported.outputs.supported == 'true' && inputs.template_artifact == ''
run: pnpm build:orcad-template --targets "$TARGET"
- name: Pack the tarball
if: steps.supported.outputs.supported == 'true'
run: |
pnpm build:packages
SOURCE_DATE_EPOCH="$(git log -1 --format=%ct)" node config/scripts/orcad-distribution/server-artifact/pack-orcad-server-artifact.mjs --template out/orcad-template --target "$TARGET" --out-dir out/orca-server
{
echo "### orca-server-linux-${{ matrix.arch }}"
echo '```'
ls -l out/orca-server
cat out/orca-server/*.sha256
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
- name: Start and pair on the runner
if: steps.supported.outputs.supported == 'true'
run: node config/scripts/orcad-distribution/server-artifact/smoke-orcad-server-artifact.mjs --archive "out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz"
# Bare images with no Node, display, GTK or X11: the tarball's own Node runs the smoke.
- name: Start and pair on minimal images
id: smoke
if: steps.supported.outputs.supported == 'true'
run: |
for image in ubuntu:24.04 debian:12-slim; do
echo "::group::$image"
docker run --rm --init \
-v "$PWD/out/orca-server:/artifacts:ro" \
-v "$PWD/config/scripts/orcad-distribution/server-artifact:/smoke:ro" \
"$image" sh -ec '
mkdir -p /tmp/runtime
tar -xzf /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz -C /tmp/runtime --strip-components=1
/tmp/runtime/runtimes/node-*/bin/node /smoke/smoke-orcad-server-artifact.mjs --archive /artifacts/orca-server-linux-${{ matrix.arch }}.tar.gz
'
echo '::endgroup::'
done
- uses: actions/upload-artifact@v7
if: steps.supported.outputs.supported == 'true'
with:
name: orca-server-linux-${{ matrix.arch }}
path: |
out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz
out/orca-server/orca-server-linux-${{ matrix.arch }}.tar.gz.sha256
if-no-files-found: error
retention-days: 7
+48
View File
@@ -1039,6 +1039,21 @@ jobs:
ref: refs/tags/${{ needs.cut.outputs.tag }}
fast_runners: false
# Server-only Linux tarballs from the same qualified template. Nothing depends on this job, so a
# failure here never holds the desktop release.
orca-server-artifact:
needs:
- cut
- orcad-template
if: ${{ !cancelled() && needs.cut.outputs.should_release == 'true' && needs.orcad-template.result == 'success' }}
permissions:
contents: read
actions: read
uses: ./.github/workflows/orca-server-artifact.yml
with:
ref: refs/tags/${{ needs.cut.outputs.tag }}
template_artifact: orcad-template
# Gate SignPath artifact requests behind blocking tests to avoid approvals for unpublishable builds.
release-preflight:
needs:
@@ -2241,6 +2256,39 @@ jobs:
--prerelease="$prerelease" \
--repo "$GITHUB_REPOSITORY"
# After publish: the draft's asset checks and undraft never see these, and a failure here only
# leaves the server tarballs missing from an already published release.
publish-orca-server-artifact:
needs:
- cut
- publish-release
- orca-server-artifact
if: ${{ !cancelled() && needs.publish-release.result == 'success' && needs.orca-server-artifact.result == 'success' && needs.orca-server-artifact.outputs.packed == 'true' && needs.cut.outputs.tag != '' }}
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write
steps:
- uses: actions/download-artifact@v8
with:
pattern: orca-server-linux-*
path: orca-server
merge-multiple: true
- name: Write the checksum manifest and upload
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TAG: ${{ needs.cut.outputs.tag }}
working-directory: orca-server
run: |
set -euo pipefail
cat orca-server-linux-x64.tar.gz.sha256 orca-server-linux-arm64.tar.gz.sha256 > orca-server-sha256sums.txt
sha256sum -c orca-server-sha256sums.txt
gh release upload "$TAG" \
orca-server-linux-x64.tar.gz \
orca-server-linux-arm64.tar.gz \
orca-server-sha256sums.txt \
--clobber --repo "$GITHUB_REPOSITORY"
post-release-e2e:
needs:
- cut
+1 -2
View File
@@ -110,8 +110,7 @@ for (const [name, options] of [
{ env: { ORCA_IDLE_REHOME_POSTGRES_URL: 'postgres://localhost:55440/relay' } }
],
['application database', { env: { DATABASE_URL: databaseUrl } }],
['one CPU', { parallelism: 1 }],
['two CPUs', { parallelism: 2 }]
['one CPU', { parallelism: 1 }]
]) {
test(`retains the original single run for ${name}`, async (t) => {
const h = start(t, options)
+1 -1
View File
@@ -560,7 +560,7 @@
1 test-no-wall-clock:src/main/pty/history/terminal-history-gc-fs-call-count.test.ts
2 test-no-wall-clock:src/main/pty/process-retirement/posix-pty-process-groups.integration.test.ts
4 test-no-wall-clock:src/main/pty/process-retirement/windows-live-tree-kill.win32.test.ts
17 test-no-wall-clock:src/main/rate-limits/service/service-account-target-selection.test.ts
5 test-no-wall-clock:src/main/rate-limits/service/service-account-target-selection.test.ts
1 test-no-wall-clock:src/main/rate-limits/service/service-cursor-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service/service-minimax-usage.test.ts
3 test-no-wall-clock:src/main/rate-limits/service/service-refresh-orchestration.test.ts
File diff suppressed because one or more lines are too long
@@ -0,0 +1,273 @@
#!/usr/bin/env node
// Packs one target's qualified template slot, its pinned Node and a launcher into the server-only
// tarball `orca serve` runs from on hosts without the desktop app.
// node pack-orcad-server-artifact.mjs --template out/orcad-template --target linux-x64-glibc [--out-dir out/orca-server]
import { createHash } from 'node:crypto'
import {
chmodSync,
copyFileSync,
mkdirSync,
readFileSync,
readdirSync,
rmSync,
writeFileSync
} from 'node:fs'
import { dirname, join, relative, resolve } from 'node:path'
import { c as createTar } from 'tar'
import {
ORCAD_NODE_RUNTIME_DIR_PREFIX,
ORCAD_RUNTIMES_DIRNAME,
ORCAD_SERVER_ENTRY_FILENAME,
ORCAD_TEMPLATE_MANIFEST_FILENAME,
ORCAD_TEMPLATE_TARGETS_DIR,
ORCAD_VERSION_FILENAME,
ORCAD_CLI_ENTRY_FILENAME,
orcadNodeRuntimeExecutable,
orcadTemplateCommonFilenames,
orcadTemplateTargetFilenames
} from '../../../../src/shared/orcad-artifacts.ts'
import { ORCAD_LOCAL_SERVE_SELECTION_ENTRY } from '../../../../src/shared/orcad-local-serve-selection.ts'
import {
NODE_RUNTIME_PIN,
nodeRuntimeExecutablePath,
nodeRuntimeReleaseUrl,
pinnedNodeRuntimeAsset
} from '../../../../src/shared/node-runtime-pin.ts'
import {
ensurePinnedNodeExecutable,
fetchPinnedFile,
pinnedNodeCacheDir
} from '../prebuilds/pinned-node-downloads.mjs'
import { extract } from '../../node-runtime/archive-identity/update-node-runtime-pin.mjs'
import { computeOrcadFullVersion } from '../server-bundle/orcad-artifact-version.mjs'
import { assertNotDarkBuild } from '../../../dark-build-switches.cjs'
import { isDirectInvocation } from '../../tool-invocation/script-entry-detection.mjs'
const root = resolve(import.meta.dirname, '../../../..')
const SLOT_DIR = 'orcad'
const LAUNCHER = 'bin/orca-ide'
/** Published name without the libc suffix: only glibc slots are published. */
export function orcaServerArtifactName(target) {
const match = /^(linux|darwin)-(x64|arm64)(?:-glibc)?$/.exec(target)
if (!match) {
throw new Error(
`No server-only artifact for ${target}; use linux-x64-glibc or linux-arm64-glibc`
)
}
return `orca-server-${match[1]}-${match[2]}`
}
function sha256(path) {
return createHash('sha256').update(readFileSync(path)).digest('hex')
}
function isExecutable(filename) {
return /(?:^|\/)(?:rg|spawn-helper)$/.test(filename)
}
function copyVerified(source, destination, expectedSha256, executable) {
mkdirSync(dirname(destination), { recursive: true })
copyFileSync(source, destination)
const actual = sha256(destination)
if (actual !== expectedSha256) {
throw new Error(`${source} hashed ${actual}; the template manifest expects ${expectedSha256}`)
}
if (executable) {
chmodSync(destination, 0o755)
}
}
/** Copies exactly the slot files the desktop deploys over SSH, each checked against the manifest. */
function stageSlot(templateDir, target, slotDir) {
const manifest = JSON.parse(
readFileSync(join(templateDir, ORCAD_TEMPLATE_MANIFEST_FILENAME), 'utf8')
)
const targetManifest = manifest.targets?.[target]
if (!targetManifest) {
throw new Error(`${templateDir} has no ${target} slot`)
}
const mobileWebAssets = Object.keys(manifest.commonSha256).filter((name) =>
name.startsWith('out/mobile-web/')
)
const common = orcadTemplateCommonFilenames([])
const commonFiles = [...new Set([...common, ...mobileWebAssets])]
for (const filename of commonFiles) {
const expected = manifest.commonSha256[filename]
if (!expected) {
throw new Error(`Template manifest omits ${filename}`)
}
copyVerified(
join(templateDir, ...filename.split('/')),
join(slotDir, ...filename.split('/')),
expected,
isExecutable(filename)
)
}
for (const filename of orcadTemplateTargetFilenames(target)) {
const expected = targetManifest.files?.[filename]
if (!expected) {
throw new Error(`Template manifest omits ${target} ${filename}`)
}
copyVerified(
join(templateDir, ORCAD_TEMPLATE_TARGETS_DIR, target, ...filename.split('/')),
join(slotDir, ...filename.split('/')),
expected,
isExecutable(filename)
)
}
// Hashed like a desktop slot without the optional browser, which this tarball omits.
const version = computeOrcadFullVersion(slotDir, { target, agentBrowserFilename: null })
writeFileSync(join(slotDir, ORCAD_VERSION_FILENAME), `${version}\n`)
return version
}
// Why sh: it must run before any Node exists on the host. ELECTRON_RUN_AS_NODE=1 is how the packaged
// app's CLI runs, and the CLI strips it from the server's environment; the other two would point
// `serve` at a desktop app this install does not have.
function launcherScript(nodeRelativePath) {
return `#!/bin/sh
# Orca server-only launcher: runs the bundled Orca CLI under the bundled Node.
set -e
self=$0
if command -v readlink >/dev/null 2>&1 && resolved=$(readlink -f -- "$self" 2>/dev/null); then
self=$resolved
fi
root=$(CDPATH= cd -- "$(dirname -- "$self")/.." && pwd -P)
node="$root/${nodeRelativePath}"
unset ORCA_APP_EXECUTABLE ORCA_SERVE_RUNTIME
ELECTRON_RUN_AS_NODE=1
export ELECTRON_RUN_AS_NODE
exec "$node" "$root/${SLOT_DIR}/${ORCAD_CLI_ENTRY_FILENAME}" "$@"
`
}
// The CLI asks `<app root>/out/main/<entry>.js` which server to run; here the answer is fixed.
function selectionEntryScript() {
return `'use strict'
// Answers \`orca serve\`'s runtime question for the server-only artifact (src/shared/orcad-local-serve-selection.ts).
const { readFileSync } = require('node:fs')
const { join } = require('node:path')
const flag = process.argv.indexOf('--app-root')
const root = flag === -1 ? join(__dirname, '..', '..', '..') : process.argv[flag + 1]
const slot = join(root, ${JSON.stringify(SLOT_DIR)})
let selection
try {
const version = readFileSync(join(slot, ${JSON.stringify(ORCAD_VERSION_FILENAME)}), 'utf8').trim()
selection = { kind: 'orcad', runtime: process.execPath, entry: join(slot, ${JSON.stringify(ORCAD_SERVER_ENTRY_FILENAME)}), version }
} catch (error) {
process.stderr.write('This Orca server install is incomplete; extract the release archive again.\\n')
process.exit(1)
}
process.stdout.write('ORCA_SERVE_RUNTIME ' + JSON.stringify(selection) + '\\n')
`
}
/** Node's notice ships with its binary; it comes from the same hash-checked archive. */
async function copyNodeLicense(target, destination) {
const asset = pinnedNodeRuntimeAsset(target)
const cacheDir = pinnedNodeCacheDir()
const archive = await fetchPinnedFile({
url: nodeRuntimeReleaseUrl(asset.source, asset.archive),
destination: join(cacheDir, asset.archive),
sha256: asset.archiveSha256
})
const topLevel = nodeRuntimeExecutablePath(target, asset.archive).replace(/\/bin\/node$/, '')
const extractDir = join(cacheDir, `license-${asset.archiveSha256.slice(0, 12)}`)
extract(archive, extractDir, `${topLevel}/LICENSE`)
copyFileSync(join(extractDir, topLevel, 'LICENSE'), destination)
}
function listEntries(dir, base = dir) {
const entries = []
for (const name of readdirSync(dir, { withFileTypes: true }).sort((a, b) =>
a.name < b.name ? -1 : a.name > b.name ? 1 : 0
)) {
const path = join(dir, name.name)
entries.push(relative(base, path))
if (name.isDirectory()) {
entries.push(...listEntries(path, base))
}
}
return entries
}
export async function packOrcaServerArtifact({ templateDir, target, outDir }) {
// A dark build's template must never ship as a server either.
assertNotDarkBuild([templateDir])
const name = orcaServerArtifactName(target)
const { version: appVersion } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
const topDir = `orca-server-${appVersion}-${name.slice('orca-server-'.length)}`
const stagingRoot = join(outDir, '.staging')
const staging = join(stagingRoot, topDir)
rmSync(stagingRoot, { recursive: true, force: true })
mkdirSync(staging, { recursive: true })
const orcadVersion = stageSlot(templateDir, target, join(staging, SLOT_DIR))
const runtimeAsset = pinnedNodeRuntimeAsset(target)
const nodeRelativePath = [
ORCAD_RUNTIMES_DIRNAME,
`${ORCAD_NODE_RUNTIME_DIR_PREFIX}${runtimeAsset.executableSha256}`,
orcadNodeRuntimeExecutable(target)
].join('/')
copyVerified(
await ensurePinnedNodeExecutable({ target }),
join(staging, ...nodeRelativePath.split('/')),
runtimeAsset.executableSha256,
true
)
const launcher = join(staging, ...LAUNCHER.split('/'))
mkdirSync(dirname(launcher), { recursive: true })
writeFileSync(launcher, launcherScript(nodeRelativePath), { mode: 0o755 })
chmodSync(launcher, 0o755)
const selectionEntry = join(staging, 'out', 'main', `${ORCAD_LOCAL_SERVE_SELECTION_ENTRY}.js`)
mkdirSync(dirname(selectionEntry), { recursive: true })
writeFileSync(selectionEntry, selectionEntryScript())
writeFileSync(
join(staging, 'VERSION'),
`orca ${appVersion}\norcad ${orcadVersion}\nnode ${NODE_RUNTIME_PIN.version}\ntarget ${target}\n`
)
copyFileSync(join(root, 'LICENSE'), join(staging, 'LICENSE'))
await copyNodeLicense(target, join(staging, ORCAD_RUNTIMES_DIRNAME, 'NODE-LICENSE'))
const archive = join(outDir, `${name}.tar.gz`)
rmSync(archive, { force: true })
createTar(
{
file: archive,
sync: true,
cwd: stagingRoot,
gzip: { level: 9 },
portable: true,
noDirRecurse: true,
// Fixed mtime: rebuilding the same tag yields the same bytes.
mtime: new Date(Number(process.env.SOURCE_DATE_EPOCH ?? 0) * 1000)
},
[topDir, ...listEntries(staging).map((entry) => `${topDir}/${entry}`)]
)
rmSync(stagingRoot, { recursive: true, force: true })
const digest = sha256(archive)
writeFileSync(`${archive}.sha256`, `${digest} ${name}.tar.gz\n`)
return { archive, sha256: digest, topDir, orcadVersion }
}
function argument(argv, name) {
const index = argv.indexOf(name)
return index === -1 ? null : (argv[index + 1] ?? null)
}
if (isDirectInvocation(import.meta.url, process.argv[1])) {
const templateDir = argument(process.argv, '--template')
const target = argument(process.argv, '--target')
if (!templateDir || !target) {
throw new Error(
'Usage: pack-orcad-server-artifact.mjs --template <dir> --target <target> [--out-dir <dir>]'
)
}
const result = await packOrcaServerArtifact({
templateDir: resolve(templateDir),
target,
outDir: resolve(argument(process.argv, '--out-dir') ?? join(root, 'out', 'orca-server'))
})
process.stdout.write(`${JSON.stringify(result)}\n`)
}
@@ -0,0 +1,135 @@
#!/usr/bin/env node
// Installs a server-only tarball the documented way, starts `orca serve --recipe-json`, then pairs a
// second CLI profile with the printed code. Uses only node: builtins so the archive's own Node can run it
// on an image that has nothing else.
// node smoke-orcad-server-artifact.mjs --archive out/orca-server/orca-server-linux-x64.tar.gz
import { execFileSync, spawnSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import {
closeSync,
existsSync,
mkdirSync,
mkdtempSync,
openSync,
readFileSync,
rmSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join, resolve } from 'node:path'
const argv = process.argv.slice(2)
const archiveArg = argv[argv.indexOf('--archive') + 1]
if (!argv.includes('--archive') || !archiveArg) {
fail('Usage: smoke-orcad-server-artifact.mjs --archive <orca-server-*.tar.gz>')
}
const archive = resolve(archiveArg)
const work = mkdtempSync(join(tmpdir(), 'orca-server-smoke-'))
const install = join(work, 'install')
const projectRoot = join(work, 'project')
const serverProfile = join(work, 'server-profile')
const clientProfile = join(work, 'client-profile')
// Linux names the CLI orca-ide, like the desktop package.
const orca = join(install, 'bin', 'orca-ide')
try {
verifyChecksum()
for (const dir of [install, projectRoot, serverProfile, clientProfile]) {
mkdirSync(dir, { recursive: true })
}
execFileSync('tar', ['-xzf', archive, '-C', install, '--strip-components=1'], {
stdio: 'inherit'
})
const version = run([orca, '--version'], serverProfile)
assert(version.status === 0, `orca --version failed:\n${version.stderr}`)
console.log(`installed ${version.stdout.trim()}`)
const started = Date.now()
const serve = run(
[orca, 'serve', '--recipe-json', '--project-root', projectRoot, '--port', '0'],
serverProfile,
{ timeout: 120_000 }
)
assert(serve.status === 0, `serve --recipe-json exited ${serve.status}:\n${serve.stderr}`)
const recipe = JSON.parse(serve.stdout.trim().split('\n').at(-1))
const pairingCode = recipe.pairingCode ?? recipe.connection?.pairingCode
assert(
typeof pairingCode === 'string' && pairingCode.length > 0,
`no pairing code: ${serve.stdout}`
)
assert(
(recipe.projectRoot ?? recipe.connection?.projectRoot) === projectRoot,
`recipe JSON names another project root: ${serve.stdout}`
)
console.log(`PASS serve --recipe-json printed a pairing code in ${Date.now() - started} ms`)
const status = run([orca, '--pairing-code', pairingCode, 'status', '--json'], clientProfile, {
timeout: 60_000
})
assert(status.status === 0, `paired status failed:\n${status.stderr}\n${status.stdout}`)
const result = JSON.parse(status.stdout).result ?? {}
assert(
result.runtime?.state === 'ready' && result.runtime?.reachable !== false,
`paired client did not reach a ready server: ${status.stdout}`
)
console.log(
`PASS a second profile paired and saw runtime ${result.runtime.runtimeId ?? ''} ready`
)
} finally {
stopServersFrom(install)
rmSync(work, { recursive: true, force: true })
}
function verifyChecksum() {
const sums = `${archive}.sha256`
if (!existsSync(sums)) {
return
}
const [expected, name] = readFileSync(sums, 'utf8').trim().split(/\s+/)
const actual = createHash('sha256').update(readFileSync(archive)).digest('hex')
assert(name === basename(archive) && actual === expected, `${archive} does not match ${sums}`)
console.log('PASS checksum')
}
// stderr goes to a file: the detached server keeps it open, and a pipe would hold spawnSync until timeout.
function run(command, profile, { timeout = 30_000 } = {}) {
const [program, ...args] = command
const log = join(work, `${basename(profile)}.stderr.log`)
const fd = openSync(log, 'a')
try {
const result = spawnSync(program, args, {
cwd: projectRoot,
encoding: 'utf8',
timeout,
stdio: ['ignore', 'pipe', fd],
env: { ...process.env, ORCA_USER_DATA_PATH: profile, ORCA_BACKGROUND_LAUNCH: '1' }
})
return { ...result, stderr: readFileSync(log, 'utf8').slice(-4000) }
} finally {
closeSync(fd)
}
}
// --recipe-json leaves the server running on purpose; this smoke must not.
function stopServersFrom(dir) {
const listing = spawnSync('ps', ['-eo', 'pid=,args='], { encoding: 'utf8' })
for (const line of (listing.stdout ?? '').split('\n')) {
const match = /^\s*(\d+)\s+(.*)$/.exec(line)
if (match && match[2].includes(dir) && Number(match[1]) !== process.pid) {
try {
process.kill(Number(match[1]), 'SIGKILL')
} catch {}
}
}
}
function assert(condition, message) {
if (!condition) {
fail(message)
}
}
function fail(message) {
console.error(`FAIL ${message}`)
process.exitCode = 1
throw new Error(message)
}
@@ -1,12 +0,0 @@
import { expect, it } from 'vitest'
import { ORCAD_ARTIFACTS } from '../../../../src/shared/orcad-artifacts.ts'
import { ORCAD_CHILD_ENTRY_POINTS, orcadChildOutputFilename } from './orcad-entry-build.mjs'
// A child built but not listed never reaches remote hosts, so its client fails there.
it.each(Object.entries(ORCAD_CHILD_ENTRY_POINTS))(
'ships the %s child bundle as an orcad artifact',
(_name, entryPoint) => {
const filenames = ORCAD_ARTIFACTS.map((artifact) => artifact.filename)
expect(filenames).toContain(orcadChildOutputFilename(entryPoint))
}
)
-1
View File
@@ -4,7 +4,6 @@
"../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../tests/e2e/terminal-agent-pane-launch.unit.test.ts",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx",
"../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts",
"../src/shared/**/*.test.ts",
"../src/shared/**/*.test.tsx",
-1
View File
@@ -8,7 +8,6 @@
"../tests/e2e/terminal-agent-pane-launch.unit.test.ts",
"../src/renderer/src/runtime/observed-provider-accounts.test.tsx",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx",
"../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts",
"../src/renderer/src/env.d.ts",
"../src/types/build-constants.d.ts",
-1
View File
@@ -14,7 +14,6 @@
"../src/renderer/src/lib/agent-session/launch/new-tab/launch-agent-in-new-tab-main-surface.test.ts",
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
"../tests/e2e/terminal-agent-pane-launch.unit.test.ts",
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx",
"../src/renderer/src/runtime/provider-accounts/observations/provider-account-observation.test-fixture.ts"
],
"compilerOptions": {
+18
View File
@@ -189,6 +189,24 @@ Use only one host mode at a time. If the Orca desktop app is already sharing tha
`orca serve` runs on Orca's own Node server (orcad) by default. If orcad can't serve on this computer, it uses the desktop app's server instead and prints one line saying why. On a packaged macOS app it uses the desktop app's server, so paired clients can still update it, unless you set `ORCA_SERVE_RUNTIME=orcad` (see [A Mac reached only over SSH](#a-mac-reached-only-over-ssh)). To always use the desktop app's server, set `ORCA_SERVE_RUNTIME=electron`.
### Install only the server on Linux
Each release also publishes the server alone for Linux x64 and arm64: orcad, the Node runtime it runs on, and the `orca-ide` CLI. It needs no desktop packages (GTK, X11, Xvfb), so it suits your own headless Linux servers, VMs and containers. It is about 60 MB to download, against 190 MB for the `.deb`. Download it, check it, and unpack it:
```bash
arch=$(uname -m | sed 's/x86_64/x64/; s/aarch64/arm64/')
base=https://github.com/stablyai/orca/releases/latest/download
curl -fsSLO "$base/orca-server-linux-$arch.tar.gz" -O "$base/orca-server-sha256sums.txt"
sha256sum --check --ignore-missing orca-server-sha256sums.txt
sudo mkdir -p /opt/orca-server
sudo tar -xzf "orca-server-linux-$arch.tar.gz" -C /opt/orca-server --strip-components=1
/opt/orca-server/bin/orca-ide serve --pairing-address <server-tailscale-ip-or-hostname>
```
To pin a release, replace `latest/download` with `download/v<version>`, and keep that release's checksum in your script rather than downloading it next to the archive. The server needs glibc 2.28 or newer (Ubuntu 20.04, Debian 10, RHEL 8 and later).
`orca-ide serve` takes the same flags as above, including `--supervise` under a service manager and `--recipe-json`. To update, stop the server, replace `/opt/orca-server` with a newer release, and start it again; paired clients cannot update it for you. For `orca-ide serve service install`, pass `--command /opt/orca-server/bin/orca-ide` or put `/opt/orca-server/bin` on `PATH`. A server-only install has no browser panes, dictation or paired web client, because those come with the desktop app.
### Limit terminal memory on a Linux server
By default, nothing caps how much memory a terminal's processes use, so one runaway job can push the whole server into the kernel's out-of-memory killer. On Linux you can cap each terminal by setting these variables in the environment that starts `orca serve` (or in its service unit):
-44
View File
@@ -3,16 +3,11 @@ import { readFile, readdir } from 'node:fs/promises'
import { existsSync } from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { pathToFileURL } from 'node:url'
const siteRoot = path.resolve(import.meta.dirname, '..')
const contentRoot = path.join(siteRoot, 'content', 'docs')
const publicRoot = path.join(siteRoot, 'public')
async function read(relativePath) {
return readFile(path.join(siteRoot, relativePath), 'utf8')
}
async function walkFiles(directory, extension) {
const entries = await readDirectory(directory)
const files = []
@@ -40,19 +35,6 @@ function isMediaPath(urlPath) {
return /\.(?:gif|jpe?g|png|webp|mp4|svg|ico)$/i.test(urlPath.split(/[?#]/, 1)[0])
}
test('docs content and navigation metadata are discoverable', async () => {
const pages = await walkFiles(contentRoot, '.mdx')
assert.ok(pages.length > 0, 'expected docs content pages')
const navigationFiles = await walkFiles(contentRoot, 'meta.json')
assert.ok(navigationFiles.length > 0, 'expected navigation metadata')
for (const file of navigationFiles) {
const metadata = JSON.parse(await readFile(file, 'utf8'))
assert.ok(metadata.title, `navigation title missing in ${file}`)
assert.ok(Array.isArray(metadata.pages), `navigation pages missing in ${file}`)
}
})
test('every local media URL referenced by docs resolves in public assets', async () => {
const files = await walkFiles(contentRoot, '.mdx')
const localUrls = new Set()
@@ -84,29 +66,3 @@ test('docs content does not link to routes that only exist on the marketing site
}
}
})
test('GIF media helpers use the shared poster and video variants', async () => {
const media = await import(pathToFileURL(path.join(siteRoot, 'src', 'lib', 'demoMedia.mjs')).href)
assert.equal(media.posterFor('/docs/orca-design-mode.gif'), '/docs/posters/orca-design-mode.jpg')
assert.equal(media.videoFor('/docs/orca-design-mode.gif'), '/docs/videos/orca-design-mode.mp4')
assert.equal(media.posterFor('/docs/tab-split.gif'), '/docs/posters/tab-split.jpg')
assert.equal(media.videoFor('/docs/tab-split.gif'), '/docs/videos/tab-split.mp4')
for (const name of ['orca-design-mode', 'tab-split']) {
assert.ok(existsSync(path.join(publicRoot, 'docs', 'posters', `${name}.jpg`)))
assert.ok(existsSync(path.join(publicRoot, 'docs', 'videos', `${name}.mp4`)))
}
})
test('OG image fonts ship with their required third-party notice', async () => {
for (const filename of ['Geist-Regular.ttf', 'Geist-Bold.ttf', 'Geist-Variable.woff2']) {
assert.ok(
existsSync(path.join(siteRoot, 'src', 'assets', 'fonts', filename)),
`missing font: ${filename}`
)
}
const notice = await read('THIRD_PARTY_NOTICES.md')
assert.match(notice, /SIL OPEN FONT LICENSE Version 1\.1/)
assert.match(notice, /Copyright \(c\) 2023 Vercel/)
})
-35
View File
@@ -1,22 +1,7 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import { stripSearchExcerptMarkdown } from '../src/components/docs/search-excerpt.mjs'
test('unterminated escaped link destinations do not backtrack exponentially', () => {
for (const prefix of ['![](', '[label](']) {
const input = prefix + '\\('.repeat(32_768)
const result = runInNewContext(
'strip(input)',
{ strip: stripSearchExcerptMarkdown, input },
{
timeout: 250
}
)
assert.equal(result, input.replace(/\\\(/g, '('))
}
})
test('link destinations retain escaped closing parentheses and literal escapes', () => {
for (const prefix of ['![label](', '[label](']) {
assert.equal(stripSearchExcerptMarkdown(prefix + 'https://example.com/a\\)b)'), 'label')
@@ -60,16 +45,6 @@ test('search excerpts preserve highlighted matches inside Markdown', () => {
)
})
test('unclosed angles finish within the excerpt budget without changing text', () => {
const input = '<'.repeat(131_072)
const result = runInNewContext(
'strip(input)',
{ strip: stripSearchExcerptMarkdown, input },
{ timeout: 250 }
)
assert.equal(result, input)
})
test('tag guards preserve malformed markup, protected code and highlighted matches', () => {
const cases = [
['<em>**bold**</em>', 'bold'],
@@ -99,13 +74,3 @@ test('tag guards preserve malformed markup, protected code and highlighted match
assert.equal(stripSearchExcerptMarkdown(input), expected, input)
}
})
test('unclosed brackets finish within the excerpt budget without changing text', () => {
const input = '['.repeat(131_072)
const result = runInNewContext(
'strip(input)',
{ strip: stripSearchExcerptMarkdown, input },
{ timeout: 250 }
)
assert.equal(result, input)
})
-52
View File
@@ -1,52 +0,0 @@
import assert from 'node:assert/strict'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import test from 'node:test'
import { pathToFileURL } from 'node:url'
const require = createRequire(import.meta.url)
const vercelRequire = createRequire(require.resolve('vercel/package.json'))
const backendsRequire = createRequire(vercelRequire.resolve('@vercel/backends/package.json'))
const zodRoot = dirname(backendsRequire.resolve('zod/package.json'))
for (const extension of ['cjs', 'js']) {
for (const entry of ['index', 'v3/index', 'v4/index']) {
test(`Vercel Zod rejects oversized collections before parsing elements (${entry}.${extension})`, async () => {
const path = join(zodRoot, `${entry}.${extension}`)
const z = extension === 'cjs' ? require(path) : await import(pathToFileURL(path).href)
let parsed = 0
const element = z.preprocess((value) => {
parsed += 1
return value
}, z.string())
for (const [schema, value, valid] of [
[z.array(element).max(2), Array(1_000).fill(0), ['a']],
[z.array(element).length(2), Array(1_000).fill(0), ['a', 'b']],
[z.set(element).max(2), new Set([1, 2, 3]), new Set(['a'])],
[z.set(element).size(2), new Set([1, 2, 3]), new Set(['a', 'b'])]
]) {
parsed = 0
for (const result of [schema.safeParse(value), await schema.safeParseAsync(value)]) {
assert.equal(result.success, false)
assert.deepEqual(
result.error.issues.map((issue) => issue.code),
['too_big']
)
}
assert.equal(parsed, 0)
assert.deepEqual(schema.parse(valid), valid)
assert.deepEqual(await schema.parseAsync(valid), valid)
}
})
}
}
test('docs Zod 4 keeps valid schemas working after the security upgrade', async () => {
const { z } = await import('zod')
const schema = z.array(z.string()).max(2)
assert.deepEqual(schema.parse(['a']), ['a'])
assert.deepEqual(
schema.safeParse([1, 2, 3]).error.issues.map((issue) => issue.code),
['too_big']
)
})
@@ -260,7 +260,7 @@ async function sendAudioChunk(
dictationId,
audioBase64: bytesToBase64(bytes),
sampleRate: MOBILE_DICTATION_PCM_SAMPLE_RATE,
seq: queue.pendingAudioBudget.nextSeq()
seq: queue.pendingAudioBudget.nextSeq(bytes.byteLength)
}
const hostDedupesResends = queue.pendingAudioBudget.hostDedupesResends
try {
@@ -1,7 +1,4 @@
import {
DICTATION_FINISH_TIMEOUT_MS,
isCurrentMobileDictationStart
} from './mobile-dictation-session-state'
import { isCurrentMobileDictationStart } from './mobile-dictation-session-state'
import { sendAcrossConnectionMove } from './mobile-dictation-audio-chunk'
import { dictationSessionLostMessage } from '../dictation/mobile-dictation-setup'
import {
@@ -10,6 +7,7 @@ import {
dictationSessionStart
} from '../dictation/mobile-dictation-operations'
import { MOBILE_DICTATION_RECONNECT_GRACE_MS } from '../../../src/shared/rpc-contract/speech-params'
import { pairedDictationFinishTimeoutMs } from '../../../src/shared/dictation-finish-deadlines'
import { rpcPayloadMember } from '../transport/rpc/rpc-reader-payload'
import { probeLivenessWhileWaiting } from '../transport/rpc/rpc-liveness-probe-while-waiting'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
@@ -57,15 +55,13 @@ export function cancelDesktopDictation(client: RpcClient, dictationId: string):
// Returns the interpreted reply: the caller reads its text only after its staleness guard.
export async function finishDesktopDictation(
client: RpcClient,
dictationId: string
dictationId: string,
sentAudioSeconds: number
): Promise<unknown> {
const timeoutMs = pairedDictationFinishTimeoutMs(sentAudioSeconds)
return dictationSessionFinish.interpret(
await sendAcrossConnectionMove(client, () =>
dictationSessionFinish.request(
client,
{ dictationId },
{ timeoutMs: DICTATION_FINISH_TIMEOUT_MS }
)
dictationSessionFinish.request(client, { dictationId }, { timeoutMs })
)
)
}
@@ -1,6 +1,7 @@
import {
DICTATION_SAMPLE_RATE,
MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES
MOBILE_DICTATION_MAX_PENDING_AUDIO_BYTES,
PCM_BYTES_PER_SAMPLE
} from '../../../src/shared/rpc-contract/speech-params'
export const MOBILE_DICTATION_PCM_SAMPLE_RATE = DICTATION_SAMPLE_RATE
@@ -15,6 +16,7 @@ export class MobileDictationPendingAudioBudget {
// Backlog not yet taken into a request; it sits at the front of the held audio.
private untakenBacklogBytes = 0
private sentChunks = 0
private sentBytes = 0
// Set at each start: a host that feeds each chunk seq once can take audio a drop left unanswered again.
hostDedupesResends = false
@@ -24,10 +26,16 @@ export class MobileDictationPendingAudioBudget {
return this.pendingBytes
}
nextSeq(): number {
// Numbers a request and counts its audio, which sets how long finish waits.
nextSeq(byteLength: number): number {
this.sentBytes += normalizeByteLength(byteLength)
return this.sentChunks++
}
get sentAudioSeconds(): number {
return this.sentBytes / (PCM_BYTES_PER_SAMPLE * MOBILE_DICTATION_PCM_SAMPLE_RATE)
}
reserveBacklog(byteLength: number): void {
const normalizedByteLength = normalizeByteLength(byteLength)
this.pendingBytes += normalizedByteLength
@@ -62,6 +70,7 @@ export class MobileDictationPendingAudioBudget {
this.backlogBytes = 0
this.untakenBacklogBytes = 0
this.sentChunks = 0
this.sentBytes = 0
this.hostDedupesResends = hostDedupesResends
}
}
@@ -36,8 +36,6 @@ export type UseMobileDictationResult = {
meter: MobileDictationMeter
}
export const DICTATION_FINISH_TIMEOUT_MS = 75_000
// An interrupted user tap needs a renderable error; only explicit user cancellation may end silently.
export const MOBILE_DICTATION_INPUT_CLOSED_ERROR_MESSAGE =
'Voice dictation stopped because this session is no longer accepting input. Try again.'
+2 -1
View File
@@ -212,7 +212,8 @@ export function useMobileDictation(options: UseMobileDictationOptions): UseMobil
if (!isCurrent() || !client) {
return
}
const finished = await finishDesktopDictation(client, dictationId)
const sentSeconds = pendingAudioBudgetRef.current.sentAudioSeconds
const finished = await finishDesktopDictation(client, dictationId, sentSeconds)
if (!isCurrent()) {
return
}
@@ -1,126 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
getTerminalRecordsFromSessionTabs,
mergeTerminalListWithKnownRecords,
mergeTerminalRecordsByCurrentOrder,
type MobileTerminalSessionTab,
type TerminalRecord
} from './mobile-terminal-records'
const lightTheme = {
mode: 'light' as const,
theme: {
background: '#ffffff',
foreground: '#111111'
}
}
const darkTheme = {
mode: 'dark' as const,
theme: {
background: '#111111',
foreground: '#eeeeee'
}
}
describe('mobile terminal records', () => {
it('keeps the known theme when a session-tab snapshot omits it', () => {
const known: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Old title', terminalTheme: darkTheme, isActive: false }
]
const snapshot: TerminalRecord[] = [{ handle: 'pty-1', title: 'Current title', isActive: true }]
expect(mergeTerminalRecordsByCurrentOrder(snapshot, known)).toEqual([
{ handle: 'pty-1', title: 'Current title', terminalTheme: darkTheme, isActive: true }
])
})
it('keeps the host pane identity when a session-tab snapshot omits it', () => {
const known: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Old title', isActive: false, agentIdentity: 'cursor' }
]
const snapshot: TerminalRecord[] = [{ handle: 'pty-1', title: 'Current title', isActive: true }]
expect(mergeTerminalRecordsByCurrentOrder(snapshot, known)).toEqual([
{ handle: 'pty-1', title: 'Current title', isActive: true, agentIdentity: 'cursor' }
])
})
it('lets an authoritative inventory replace or clear an earlier host identity', () => {
const known: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Terminal', isActive: true, agentIdentity: 'cursor' }
]
for (const agentIdentity of ['claude', undefined]) {
const listed: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Terminal', isActive: true, agentIdentity }
]
expect(mergeTerminalListWithKnownRecords(listed, known, [])[0]?.agentIdentity).toBe(
agentIdentity
)
}
})
it('keeps session-tab terminal themes when terminal.list omits them', () => {
const terminalList: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Terminal', isActive: true },
{ handle: 'pty-2', title: 'Logs', isActive: false }
]
const currentTerminals: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true }
]
const sessionTabs: MobileTerminalSessionTab[] = [
{
type: 'terminal',
id: 'term-1::leaf-1',
title: 'Terminal',
terminal: 'pty-1',
terminalTheme: lightTheme,
isActive: true
}
]
expect(mergeTerminalListWithKnownRecords(terminalList, currentTerminals, sessionTabs)).toEqual([
{ handle: 'pty-1', title: 'Terminal', terminalTheme: lightTheme, isActive: true },
{ handle: 'pty-2', title: 'Logs', isActive: false }
])
})
it('falls back to the current terminal theme while waiting for session tabs', () => {
const terminalList: TerminalRecord[] = [{ handle: 'pty-1', title: 'Terminal', isActive: true }]
const currentTerminals: TerminalRecord[] = [
{ handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true }
]
expect(mergeTerminalListWithKnownRecords(terminalList, currentTerminals, [])).toEqual([
{ handle: 'pty-1', title: 'Terminal', terminalTheme: darkTheme, isActive: true }
])
})
const record = (over: Partial<TerminalRecord> & { handle: string }): TerminalRecord => ({
title: 'Terminal',
terminalTheme: undefined,
isActive: false,
...over
})
const terminalTab = (handle: string): MobileTerminalSessionTab => ({
id: `tab-${handle}`,
type: 'terminal',
terminal: handle,
title: 'Terminal',
isActive: false
})
it('keeps the merge additive so absence only schedules the sweep', () => {
const held = [
record({ handle: 'pty-1', connected: true }),
record({ handle: 'pty-2', connected: true })
]
const tabs = [terminalTab('pty-1')]
expect(
mergeTerminalRecordsByCurrentOrder(getTerminalRecordsFromSessionTabs(tabs), held).map(
(terminal) => terminal.handle
)
).toEqual(['pty-1', 'pty-2'])
})
})
@@ -1,38 +0,0 @@
import { terminalInputSend } from './mobile-terminal-operations'
import { describe, expect, it, vi } from 'vitest'
import { sendTerminalLiveAccessoryRawBytes } from './terminal-live-accessory-raw-send'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
function captureClient(
result: Promise<unknown> = Promise.resolve({
id: 'send',
ok: true,
result: { send: { handle: 'terminal-a', accepted: true, bytesWritten: 1 } },
_meta: { runtimeId: 'test-runtime' }
})
) {
const sendRequest = vi.fn(() => result)
return { client: { sendRequest } as unknown as Pick<RpcClient, 'sendRequest'>, sendRequest }
}
const BASE_ARGS = {
sendTerminalUserInput: terminalInputSend.request,
targetHandle: 'terminal-a',
activeHandle: 'terminal-a',
activeSessionTabType: 'terminal',
connState: 'connected',
bytes: '',
deviceToken: 'tok'
} as const
describe('terminal live accessory raw send', () => {
it('drops the bytes when the terminal selection went stale mid-flush', async () => {
const { client, sendRequest } = captureClient()
await expect(
sendTerminalLiveAccessoryRawBytes({ ...BASE_ARGS, client, activeHandle: 'terminal-b' })
).resolves.toBe(false)
expect(sendRequest).not.toHaveBeenCalled()
})
})
@@ -1,32 +0,0 @@
import { describe, expect, it } from 'vitest'
import { reduceTerminalFrameHeightRefit } from './terminal-viewport-refit-state'
describe('terminal viewport refit', () => {
it('re-defers a height refit if the keyboard reopens before the debounce fires', () => {
let r = reduceTerminalFrameHeightRefit(
{ frameHeight: 600, keyboardVisible: true, pending: false },
{ type: 'frame-height', height: 520 }
)
expect(r.shouldRefit).toBe(false)
expect(r.state.pending).toBe(true)
r = reduceTerminalFrameHeightRefit(r.state, { type: 'keyboard-visibility', visible: false })
expect(r.shouldRefit).toBe(true)
// Reopen inside debounce; the timer must preserve the pending refit instead of reflowing while typing.
r = reduceTerminalFrameHeightRefit(r.state, { type: 'keyboard-visibility', visible: true })
const committed = reduceTerminalFrameHeightRefit(r.state, { type: 'refit-committed' })
expect(committed.shouldRefit).toBe(false)
expect(committed.state.pending).toBe(true)
const rescheduled = reduceTerminalFrameHeightRefit(committed.state, {
type: 'keyboard-visibility',
visible: false
})
expect(rescheduled.shouldRefit).toBe(true)
const ran = reduceTerminalFrameHeightRefit(rescheduled.state, { type: 'refit-committed' })
expect(ran.shouldRefit).toBe(true)
expect(ran.state.pending).toBe(false)
})
})
@@ -118,7 +118,7 @@ so the projection has a temporal dimension instead of relying on where a checkpo
Any transition the product schedules for itself is recorded at the time it actually fires: change a
request deadline or the search debounce by any amount, in either direction, and a recorded number
moves. Granularity is exact milliseconds, because the fake timers fire at their scheduled time and
never coalesce; `recording-runner.test.ts` pins a 5 ms deadline settling at exactly `settledAt: 5`.
never coalesce.
A checkpoint's own clock is not recorded. It is always the sum of the scripted `advance` steps, so
it is a function of the scenario rather than of the code under test; `run-recording.ts` asserts that
@@ -1,50 +0,0 @@
import { resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { pilotMountAdapters } from './pilot-mount-adapters'
import { runRecording } from './run-recording'
import { readScenarios } from './scenario-input'
import { vitestRecordingScheduler } from './vitest-recording-scheduler'
const root = resolve(import.meta.dirname, '../../../..')
const manifest = readScenarios(
process.env.RPC_FOUNDATION_SCENARIOS ??
resolve(root, 'mobile/rpc-foundation/pilot-scenarios.json')
).scenarios
describe('a mounted screen', () => {
// Drive the real panel/context/socket so declared props reach wire params and refusal triggers fallback.
it('sends what the screen sends, with no substitute shaping a param', async () => {
const scenario = manifest.find(
(candidate) => candidate.id === 'files-explorer-legacy-fallback'
)!
const { adapters } = pilotMountAdapters(root, { device: scenario })
const recording = await runRecording(
scenario,
adapters[scenario.operation]!,
vitestRecordingScheduler()
)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a recorded sender entry has a name and three positional argument slots.
const sender = recording.checkpoints.at(-1)!.observation.sender as {
name: string
args: { name: string; value: unknown }[]
}[]
expect(
sender.map((entry) => ({
name: entry.name,
params: entry.args[1]?.value,
options: entry.args[2]?.value
}))
).toEqual([
{
name: 'files.readDir#1',
params: { relativePath: '', worktree: 'id:wt-files', limit: 500 },
options: { failWhenDisconnected: true }
},
{
name: 'files.list#1',
params: { worktree: 'id:wt-files' },
options: { failWhenDisconnected: true }
}
])
})
})
@@ -1,34 +0,0 @@
import { describe, expect, it } from 'vitest'
import { ScriptedRpcTransport } from './scripted-rpc-transport'
import { vitestRecordingScheduler } from './vitest-recording-scheduler'
describe('recording boundaries', () => {
it('requires logical bindings plus matching params for concurrent same-method calls', async () => {
const clock = vitestRecordingScheduler()
await clock.start()
const transport = new ScriptedRpcTransport(clock.elapsed)
try {
const left = transport.client.sendRequest('files.list', { worktree: 'A' })
const right = transport.client.sendRequest('files.list', { worktree: 'B' })
await clock.flush()
expect(() => transport.complete('files.list#1', { worktree: 'A' }, {})).toThrow(
'logical binding'
)
expect(() => transport.bind('left', 'files.list#1', { worktree: 'B' })).toThrow(
'params mismatch'
)
transport.bind('left', 'files.list#1', { worktree: 'A' })
transport.bind('right', 'files.list#2', { worktree: 'B' })
transport.complete('right', { worktree: 'B' }, { ok: true, result: [] })
transport.complete('left', { worktree: 'A' }, { ok: true, result: [] })
await Promise.all([left, right])
} finally {
await transport.dispose()
await clock.flush()
transport.causality.assertTransparentCalls()
transport.causality.close()
clock.stop()
}
})
})
@@ -47,7 +47,7 @@ vi.mock('../../diagnostics/connection/connection-log-background-flush', () => ({
}))
import { RpcClientProvider } from './client-context'
import { useDisconnectHostClient, useForceReconnect, useHostClient } from './host-client-hooks'
import { useDisconnectHostClient, useHostClient } from './host-client-hooks'
import { useAllHostClients } from './use-all-host-clients'
import { useRelayRecoveryStatus } from './client-context-connection-metrics'
@@ -168,45 +168,6 @@ beforeEach(() => {
})
describe('useHostClient', () => {
it('shows connecting while a reused screen resolves an uncached host', async () => {
const client = makeFakeClient('connected')
connectMock.mockReturnValue(client)
loadHostsMock.mockResolvedValueOnce([HOST]).mockReturnValueOnce(new Promise<never>(() => {}))
let selectedHostId = HOST.id
let renderTick = 0
const stateByRenderTick = new Map<number, ConnectionState>()
let renderer: ReactTestRenderer | null = null
function Probe(): null {
stateByRenderTick.set(renderTick, useHostClient(selectedHostId).state)
return null
}
try {
await act(async () => {
renderer = create(createElement(RpcClientProvider, null, createElement(Probe)))
await Promise.resolve()
})
expect(stateByRenderTick.get(0)).toBe('connected')
// Keep host swaps amber during asynchronous profile/keychain loading.
selectedHostId = 'missing-host'
renderTick = 1
await act(async () => {
renderer?.update(createElement(RpcClientProvider, null, createElement(Probe)))
})
expect(stateByRenderTick.get(1)).toBe('connecting')
renderTick = 2
await act(async () => {
renderer?.update(createElement(RpcClientProvider, null, createElement(Probe)))
})
expect(stateByRenderTick.get(2)).toBe('connecting')
} finally {
act(() => renderer?.unmount())
}
})
it('drops the closed client when the host entry is removed', async () => {
const fake = makeFakeClient('connected')
connectMock.mockReturnValue(fake)
@@ -226,38 +187,6 @@ describe('useHostClient', () => {
harness.unmount()
})
it('keeps Retry amber through forceReconnect instead of grey-then-amber', async () => {
const first = makeFakeClient('connected')
const second = makeFakeClient('connecting')
connectMock.mockReturnValueOnce(first).mockReturnValueOnce(second)
loadHostsMock.mockResolvedValue([HOST])
const states: ConnectionState[] = []
let forceReconnect: ((hostId: string) => Promise<void>) | null = null
let renderer: ReactTestRenderer | null = null
function Probe(): null {
forceReconnect = useForceReconnect()
states.push(useHostClient(HOST.id).state)
return null
}
try {
await act(async () => {
renderer = create(createElement(RpcClientProvider, null, createElement(Probe)))
await Promise.resolve()
})
expect(states.at(-1)).toBe('connected')
await act(async () => {
await forceReconnect?.(HOST.id)
})
expect(first.closeMock).toHaveBeenCalled()
expect(states.at(-1)).toBe('connecting')
expect(states).not.toContain('disconnected')
} finally {
act(() => renderer?.unmount())
}
})
})
describe('useAllHostClients', () => {
@@ -3,12 +3,10 @@ import {
dependencies,
FakeLogicalClient,
FakeRelaySession,
FakeSession,
host,
relay
} from './mobile-endpoint-supervisor-test-fakes'
import { MobileEndpointSupervisor } from './mobile-endpoint-supervisor'
import { createStableLogicalRpcClient } from './stable-logical-rpc-client'
vi.mock('react-native', () => ({ Platform: { OS: 'ios' } }))
vi.mock('expo-secure-store', () => ({ WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'when-unlocked' }))
@@ -55,58 +53,6 @@ describe('mobile endpoint supervisor relay race after a mid-session LAN loss', (
supervisor.stop()
})
it('paces relay dials by the shared cooldown while relay is also unreachable', async () => {
// A relay socket that never authenticates fails its migration.
const { logical, openRelay, supervisor } = await startOnLan(
vi.fn(() => new FakeRelaySession('connecting'))
)
for (let i = 0; i < 60; i++) {
redialDirect(logical)
await vi.advanceTimersByTimeAsync(2_000)
}
// 60 redials in 2 min; each attempt is a cell dial plus a director-resolved retry.
// Racing every redial would open 120 sockets; the 0.5 s→30 s backoff keeps it under 20.
expect(openRelay.mock.calls.length).toBeGreaterThan(0)
expect(openRelay.mock.calls.length).toBeLessThanOrEqual(20)
supervisor.stop()
})
it('races each slow LAN blip once and closes the relay socket the LAN beat', async () => {
// The real logical client owns the lost-race close: it aborts after relay authentication.
const direct = new FakeSession('connected')
const logical = createStableLogicalRpcClient(direct, 'lan')
const relaySessions: FakeRelaySession[] = []
const openRelay = vi.fn(() => {
const session = new FakeRelaySession('connecting')
relaySessions.push(session)
return session
})
const supervisor = new MobileEndpointSupervisor(
logical,
host.id,
relay,
dependencies({ openRelay, randomBytes: () => new Uint8Array([255, 255]) })
)
await supervisor.start()
for (let flap = 0; flap < 10; flap++) {
direct.publishState('reconnecting')
direct.publishState('connecting')
await vi.advanceTimersByTimeAsync(3_000)
direct.publishState('connected')
relaySessions.at(-1)?.publishState('connected')
await vi.advanceTimersByTimeAsync(10_000)
}
// Accepted cost: one relay dial per blip past the 2.5 s head start, each closed once it loses.
expect(openRelay).toHaveBeenCalledTimes(10)
expect(relaySessions.every((session) => session.close.mock.calls.length > 0)).toBe(true)
expect(logical.getActivePath()).toBe('lan')
supervisor.stop()
})
it('drops a race deferred by cooldown once the LAN comes back', async () => {
const { logical, openRelay, supervisor } = await startOnLan(
vi.fn(() => new FakeRelaySession('connecting'))
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveHostEndpointEdit } from './host-endpoint-edit'
describe('resolveHostEndpointEdit', () => {
it.each([
['ws://192.168.1.10:6768', 'wss://tunnel.example.com', 'wss://tunnel.example.com:443'],
['wss://old.example.com:8443', ' WSS://tunnel.example.com ', 'wss://tunnel.example.com:443'],
['ws://192.168.1.10:6768', 'wss://[2001:db8::2]', 'wss://[2001:db8::2]:443'],
['ws://192.168.1.10:6768', 'wss://tunnel.example.com:9443', 'wss://tunnel.example.com:9443'],
['ws://192.168.1.10:6768', 'tunnel.example.com', 'ws://tunnel.example.com:6768'],
[
'wss://old.example.com:8443/orca?route=runtime',
'wss://tunnel.example.com',
'wss://tunnel.example.com:443/orca?route=runtime'
]
])(
'resolves explicit secure URLs independently of the saved port (%s → %s)',
(stored, input, expected) => {
expect(resolveHostEndpointEdit(stored, input)).toEqual({
kind: 'changed',
endpoint: expected
})
}
)
it.each([
['surrounding whitespace', ' desk.example.com '],
['hostname case', 'DESK.EXAMPLE.COM'],
['explicit default port', 'desk.example.com:443'],
['percent-encoded hostname', 'wss://%64esk.example.com:443']
])('preserves routed endpoint bytes for equivalent %s', (_label, input) => {
const stored = 'wss://Desk.Example.com/%6Fruntime?route=%72ed'
expect(resolveHostEndpointEdit(stored, input)).toEqual({
kind: 'unchanged',
endpoint: stored
})
})
it('preserves the hidden route when the authority changes', () => {
expect(
resolveHostEndpointEdit('wss://old.example.com/%6Fruntime?route=%72ed', 'new.example.com')
).toEqual({
kind: 'changed',
endpoint: 'wss://new.example.com:443/%6Fruntime?route=%72ed'
})
})
})
@@ -1,26 +0,0 @@
import { describe, expect, it } from 'vitest'
import { displayHostEndpoint, normalizeHostEndpoint } from './host-endpoint'
describe('normalizeHostEndpoint', () => {
it('preserves explicit ws :80 and wss :443 instead of rewriting to fallback', () => {
expect(normalizeHostEndpoint('ws://192.168.1.10:80', { fallbackPort: '6768' })).toEqual({
ok: true,
endpoint: 'ws://192.168.1.10:80'
})
expect(normalizeHostEndpoint('wss://desk.example:443', { fallbackPort: '6768' })).toEqual({
ok: true,
endpoint: 'wss://desk.example:443'
})
expect(displayHostEndpoint('ws://192.168.1.10:80')).toBe('192.168.1.10:80')
expect(displayHostEndpoint('wss://desk.example:443')).toBe('desk.example:443')
})
it('preserves wss when re-normalizing bare host:port via fallbackScheme', () => {
expect(
normalizeHostEndpoint('desk.example:8443', { fallbackScheme: 'wss', fallbackPort: '8443' })
).toEqual({
ok: true,
endpoint: 'wss://desk.example:8443'
})
})
})
@@ -85,20 +85,6 @@ describe('host name identity', () => {
}
describe('legacy classification', () => {
it('does not re-classify an adopted machine name once identity fields exist', async () => {
// A record the descriptor writer already touched: non-generated name, no override.
storedHostsRaw = JSON.stringify([
{
...GENERATED_HOST,
name: 'm4airs-Air',
lastKnownMachineName: 'm4airs-Air',
lastKnownHostPlatform: 'darwin'
}
])
const hosts = await loadHosts()
expect(hosts[0]?.personalName).toBeUndefined()
})
it('drops only an identity value this build cannot read, never the paired host', async () => {
// A newer build's platform, or an empty string, as a rolled-back app would find them.
storedHostsRaw = JSON.stringify([
@@ -119,39 +105,7 @@ describe('host name identity', () => {
})
})
describe('updateHostDescriptor', () => {
it('clears a stale machine name when a live host stops reporting one', async () => {
await updateHostDescriptor(GENERATED_HOST.id, {
machineName: 'm4airs-Air',
platform: 'darwin'
})
await updateHostDescriptor(GENERATED_HOST.id, { machineName: null, platform: 'darwin' })
const record = stored().find(({ id }) => id === GENERATED_HOST.id)
expect(record?.lastKnownMachineName).toBeUndefined()
expect(record?.name).toBe('m4airs-Air')
})
})
describe('re-pair', () => {
it('preserves the override and descriptor a pairing save knows nothing about', async () => {
await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' })
await savePairedHost({
id: TYPED_HOST.id,
name: 'Windows-Low Spec',
endpoint: 'ws://10.0.0.9:6768',
deviceToken: 'fresh-token',
publicKeyB64: TYPED_HOST.publicKeyB64,
lastConnected: 99
})
expect(stored().find(({ id }) => id === TYPED_HOST.id)).toMatchObject({
name: 'Windows-Low Spec',
personalName: 'Windows-Low Spec',
lastKnownMachineName: 'm4airs-Air',
lastKnownHostPlatform: 'darwin',
endpoint: 'ws://10.0.0.9:6768'
})
})
it('does not roll back identity changed since a connection took its profile snapshot', async () => {
await updateHostDescriptor(TYPED_HOST.id, { machineName: 'Studio', platform: 'darwin' })
// Use a connection-held snapshot to prove saves cannot roll back later identity changes.
@@ -168,14 +122,4 @@ describe('host name identity', () => {
})
})
})
describe('phone override edit', () => {
it('clearing the override returns to the desktop-reported name', async () => {
await updateHostDescriptor(TYPED_HOST.id, { machineName: 'm4airs-Air', platform: 'darwin' })
await updateHostNameAndEndpoint(TYPED_HOST.id, { personalName: null })
const record = stored().find(({ id }) => id === TYPED_HOST.id)
expect(record?.personalName).toBeUndefined()
expect(record?.name).toBe('m4airs-Air')
})
})
})
@@ -1,92 +0,0 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
import * as SecureStore from 'expo-secure-store'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { loadHosts, resetHostStoreForTests, updateHostNameAndEndpoint } from './host-store'
import { resetMobileRelayHostOverlayStoreForTests } from './mobile-relay-host-overlay-store'
vi.mock('@react-native-async-storage/async-storage', () => ({
default: {
getItem: vi.fn(),
setItem: vi.fn(),
removeItem: vi.fn()
}
}))
vi.mock('expo-secure-store', () => ({
getItemAsync: vi.fn(),
setItemAsync: vi.fn(),
deleteItemAsync: vi.fn(),
WHEN_UNLOCKED_THIS_DEVICE_ONLY: 'WHEN_UNLOCKED_THIS_DEVICE_ONLY'
}))
vi.mock('react-native', () => ({
Platform: { OS: 'ios' }
}))
describe('relay routing after a host edit', () => {
const OVERLAY_KEY = 'orca:mobile-relay:host-overlays:v2'
const OLD_ENDPOINT = 'ws://192.168.1.10:6768'
const NEW_ENDPOINT = 'ws://192.168.1.20:6768'
const relay = {
v: 1 as const,
directorUrl: 'https://relay.onorca.dev',
cellUrl: 'https://relay-c1.onorca.dev',
assignmentEpoch: 7,
relayHostId: 'AbCdEf0123_-xyZ9',
e2eeFraming: 2 as const
}
const storage = new Map<string, string>()
beforeEach(() => {
resetHostStoreForTests()
resetMobileRelayHostOverlayStoreForTests()
storage.clear()
storage.set(
'orca:hosts',
JSON.stringify([
{ id: 'host-1', name: 'Desk', endpoint: OLD_ENDPOINT, publicKeyB64: 'pk', lastConnected: 1 }
])
)
// An older build's record: a copy of the row's address beside the relay.
storage.set(
OVERLAY_KEY,
JSON.stringify([
{
v: 2,
hostId: 'host-1',
endpoints: [
{ id: 'direct-primary', kind: 'lan', url: OLD_ENDPOINT },
{ id: 'relay-primary', kind: 'relay', url: 'wss://relay-c1.onorca.dev/v1/connect/id' }
],
relayHostId: relay.relayHostId,
relay
}
])
)
vi.mocked(AsyncStorage.getItem).mockReset()
vi.mocked(AsyncStorage.getItem).mockImplementation(async (key) => storage.get(key) ?? null)
vi.mocked(AsyncStorage.setItem).mockReset()
vi.mocked(AsyncStorage.setItem).mockImplementation(async (key, value) => {
storage.set(key, value)
})
vi.mocked(SecureStore.getItemAsync).mockResolvedValue('device-token')
vi.mocked(SecureStore.setItemAsync).mockReset()
})
it('loads only the edited address, whatever an older overlay stored', async () => {
await updateHostNameAndEndpoint('host-1', { endpoint: NEW_ENDPOINT })
const [host] = await loadHosts()
expect(host).toEqual({
id: 'host-1',
name: 'Desk',
personalName: 'Desk',
endpoint: NEW_ENDPOINT,
publicKeyB64: 'pk',
lastConnected: 1,
deviceToken: 'device-token',
relay
})
})
})
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import './mobile-relay-host-overlay'
import type { MobileRelayHostOverlay } from './mobile-relay-host-overlay'
const asyncStorageMock = vi.hoisted(() => ({
getItem: vi.fn(),
@@ -166,29 +165,6 @@ describe('host-store list mutations', () => {
).resolves.toBe('replacement-token')
})
it('clears stale relay state when an existing host is re-paired direct-only', async () => {
const overlay: MobileRelayHostOverlay = {
v: 2,
hostId: HOST_ONE.id,
endpoints: [
{ id: 'direct-primary', kind: 'lan', url: HOST_ONE.endpoint },
{
id: 'relay-primary',
kind: 'relay',
url: 'wss://relay-c1.onorca.dev/v1/connect/AbCdEf0123_-xyZ9'
}
],
relayHostId: HOST_ONE_RELAY.relayHostId,
relay: HOST_ONE_RELAY
}
storedOverlayRaw = JSON.stringify([overlay])
await savePairedHost({ ...HOST_ONE, deviceToken: 'replacement-token' })
expect(JSON.parse(storedOverlayRaw!)).toEqual([])
expect(secureStoreMock.deleteItemAsync).not.toHaveBeenCalled()
})
it('refuses an early same-key token write without durable cleanup intent', async () => {
const replacement = {
...HOST_TWO,
@@ -1,79 +0,0 @@
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AgentSessionJournalIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
import { openAgentSessionJournal } from '../native-chat/agent-session-journal/journal-store-factory'
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
import {
closeTestJournalHostDatabases,
openTestJournalHostDatabase
} from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
const IDENTITY: AgentSessionJournalIdentity = {
sessionId: 'session-1',
workspaceId: 'workspace-1',
hostId: 'host-1',
agent: 'claude',
providerHandle: claudeProviderHandle('provider-1', 'leaf-1')
}
/** Informational frame shape from CLI 2.1.280. */
function informational(
level: 'info' | 'notice' | 'suggestion' | 'warning',
content: string
): Record<string, unknown> {
return {
type: 'system',
subtype: 'informational',
content,
level,
uuid: `5d3c1f0e-7a2b-4c6d-9e8f-00000000000${level.length}`,
session_id: 'provider-1'
}
}
let root = ''
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'orca-claude-informational-'))
})
afterEach(async () => {
await closeTestJournalHostDatabases()
await rm(root, { recursive: true, force: true })
})
async function itemsFor(frames: Record<string, unknown>[]) {
const journal = await openAgentSessionJournal({
identity: IDENTITY,
database: openTestJournalHostDatabase(root),
now: () => 1_700_000_000_000,
mintEpoch: () => 'epoch-1'
})
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
deferred.bind({ journal, fence: 1, publish: vi.fn() })
const translator = createClaudeJournalTranslator({ sink: deferred.sink, fallbackIdPrefix: '1' })
for (const frame of frames) {
translator.handle({ type: 'message', sessionId: 'orca-session', message: frame })
await deferred.drained()
}
return journal.snapshot().items.map((item) => item.body)
}
describe('a Claude informational frame', () => {
it.each(['info', 'notice', 'suggestion'] as const)('writes no row at level %s', async (level) => {
expect(await itemsFor([informational(level, `A ${level} note`)])).toEqual([])
})
it('writes its own words as one warning row at level warning', async () => {
const content =
'UserPromptSubmit operation blocked by hook: secrets are not allowed\n\nOriginal prompt: deploy it'
const items = await itemsFor([informational('warning', content)])
expect(items).toEqual([{ kind: 'status', tone: 'warning', text: content }])
})
})
@@ -55,7 +55,6 @@ describe('claude model catalog probe', () => {
it.each([
[[], [], ['/orca-probe', '/orca-probe'], 'user,project,local'],
[['node_modules/claude/cli.js'], [], ['/chat-a', '/chat-b'], 'user'],
[['--env-file=work env', '--', 'claude'], [], ['/chat-a', '/chat-b'], 'user'],
[[], ['--settings', 'settings.json'], ['/chat-a', '/chat-b'], 'user']
])(
'lists prefix %j with arguments %j from %j, reading %s settings',
@@ -1,118 +0,0 @@
import { performance } from 'node:perf_hooks'
import { afterEach, expect, it, vi } from 'vitest'
import { createClaudeFullAccessPolicy } from './claude-full-access-policy'
const SESSION = '819cf9f8-e43c-4ad7-b50f-54aa158a726a'
const CHUNK_BYTES = 1000
afterEach(() => {
vi.restoreAllMocks()
})
const line = (frame: Record<string, unknown>): string => `${JSON.stringify(frame)}\n`
type Work = { chars: number; parses: number; newlineSearched: number; screened: number }
/** Drives the real policy and counts the characters it searches, so a rescan cannot hide in time. */
function observeWire(frames: number): Work {
const delta = line({
type: 'stream_event',
event: { type: 'content_block_delta', delta: { type: 'text_delta', text: 'ok — '.repeat(8) } },
session_id: SESSION
})
// A tool result spanning thousands of chunks, as large file reads do.
const longLine = line({
type: 'user',
message: {
role: 'user',
content: [{ type: 'tool_result', content: 'y'.repeat(frames * 3000) }]
},
session_id: SESSION
})
const expected: [string, boolean][] = []
let wire = ''
for (let index = 0; index < frames; index += 1) {
wire += delta
if (index % 10 === 0) {
const mode = index % 20 === 0 ? 'plan' : 'bypassPermissions'
wire += line({ type: 'system', subtype: 'status', permissionMode: mode, session_id: SESSION })
wire += line({
type: 'control_request',
request_id: `r${index}`,
request: { subtype: 'can_use_tool', tool_name: 'Bash', input: {}, tool_use_id: `t${index}` }
})
expected.push([`r${index}`, mode === 'bypassPermissions'])
}
if (index === frames / 2) {
wire += longLine
}
}
const bytes = Buffer.from(wire)
const policy = createClaudeFullAccessPolicy(SESSION)
// Node's own internals keep their original string methods, so these count only the policy's calls.
const { indexOf, includes } = String.prototype
let newlineSearched = 0
let screened = 0
const parse = vi.spyOn(JSON, 'parse')
const searches = vi.spyOn(String.prototype, 'indexOf').mockImplementation(function (
this: string,
search: string,
position?: number
) {
const found = indexOf.call(this, search, position)
newlineSearched += (found === -1 ? this.length : found + search.length) - (position ?? 0)
return found
})
const screens = vi.spyOn(String.prototype, 'includes').mockImplementation(function (
this: string,
search: string,
position?: number
) {
screened += this.length
return includes.call(this, search, position)
})
const started = performance.now()
// Fixed-size chunks split frames and multibyte characters, as pipe reads do.
try {
for (let offset = 0; offset < bytes.length; offset += CHUNK_BYTES) {
policy.observe(bytes.subarray(offset, offset + CHUNK_BYTES))
}
} finally {
searches.mockRestore()
screens.mockRestore()
}
const elapsedMs = performance.now() - started
const parses = parse.mock.calls.length
parse.mockRestore()
const work = { chars: wire.length, parses, newlineSearched, screened }
console.info('claude-full-access-policy-perf', {
frames,
bytes: bytes.length,
...work,
elapsedMs
})
// Newlines are looked for in new text only, and each completed line is screened at most twice,
// checked per size so a rescanning policy fails here before the larger run exhausts memory.
expect(newlineSearched).toBeLessThanOrEqual(wire.length)
expect(screened).toBeLessThanOrEqual(2 * wire.length)
// Only mode reports and permission requests are parsed; deltas and the long line never are.
expect(parses).toBe(expected.length * 2)
// Unread requests stay until the SDK hands each to canUseTool, however many queue up.
expect(policy.retained()).toEqual({ partialChars: 0, requests: expected.length })
for (const [requestId, fullAccess] of expected) {
expect(policy.allows(requestId), requestId).toBe(fullAccess)
}
expect(policy.retained()).toEqual({ partialChars: 0, requests: 0 })
return work
}
it('searches each stdout character a bounded number of times, however long a line grows', () => {
const small = observeWire(300)
const large = observeWire(3000)
// Ten times the output, including a ten times longer line, costs ten times the work.
expect(large.newlineSearched).toBeLessThanOrEqual(10 * small.newlineSearched + CHUNK_BYTES)
expect(large.screened).toBeLessThanOrEqual(10 * small.screened + CHUNK_BYTES)
expect(large.parses).toBe(10 * small.parses)
})
@@ -14,7 +14,7 @@ import { HOST_TEST_SESSION as SESSION } from '../../native-chat/agent-session-wi
const claudeTurnEnds = (connection: Parameters<typeof claudeFrame>[0]) =>
claudeFrame(connection, { type: 'system', subtype: 'session_state_changed', state: 'idle' })
it.each(['low', 'high', undefined])(
it.each(['high', undefined])(
'admits accepted high independently of resolved effort (effective %s)',
async (effective) => {
const models = [
@@ -46,16 +46,6 @@ const SETTINGS = {
effective: { model: 'haiku' },
sources: [{ source: 'userSettings', settings: { model: 'haiku' } }],
applied: { model: 'claude-haiku-4-5-20251001', effort: null, advisor: null, ultracode: false }
},
envSonnet: {
effective: {},
sources: [],
applied: { model: 'claude-sonnet-5', effort: 'high', advisor: null, ultracode: false }
},
settingsHaikuEnvSonnet: {
effective: { model: 'haiku' },
sources: [{ source: 'userSettings', settings: { model: 'haiku' } }],
applied: { model: 'claude-sonnet-5', effort: 'high', advisor: null, ultracode: false }
}
}
@@ -69,29 +59,7 @@ function startedWithoutATurn(settings: unknown) {
})
}
async function readCurrent(settings: unknown) {
const adapter = await acquired(startedWithoutATurn(settings))
return (await adapter.readOptions({ sessionId: 'session-1', fence: 7 })).current
}
describe('Claude model before the first turn', () => {
it.each([
['nothing overrides the default', SETTINGS.noOverride, 'claude-opus-5-5[1m]', 'medium'],
['settings name a model', SETTINGS.settingsHaiku, 'claude-haiku-4-5-20251001', undefined],
['the env names a model', SETTINGS.envSonnet, 'claude-sonnet-5', 'high'],
['the env overrides the settings', SETTINGS.settingsHaikuEnvSonnet, 'claude-sonnet-5', 'high']
])(
'names what Claude will apply when %s, unconfirmed',
async (_case, settings, model, effort) => {
const current = await readCurrent(settings)
expect(current.model).toBe(model)
expect(current.effort).toBe(effort)
expect(current.confirmed ?? []).not.toContain('model')
expect(current.confirmed ?? []).not.toContain('effort')
}
)
it('uses native applied effort despite settings High, before and after a reply', async () => {
// Claude Code 2.1.318: no flag applies Medium; --effort low applies Low.
const claude = startedWithoutATurn({
@@ -156,13 +124,6 @@ describe('Claude model before the first turn', () => {
await adapter.closeAll()
})
it('marks an unknown applied model as defaulted for the host to resolve', async () => {
const current = await readCurrent({ effective: {}, sources: [] })
expect(current.defaulted).toEqual(['model'])
expect(current.effort).toBeUndefined()
})
it('lets the first turn confirm or correct it', async () => {
const claude = startedWithoutATurn(SETTINGS.settingsHaiku)
const adapter = await acquired(claude)
@@ -32,7 +32,7 @@ it('resolves a custom Claude command against the login shell PATH', async () =>
}
})
it('names Orca as the Claude client unless the launch environment sets one', () => {
it('isolates inherited Claude stamps before applying launch settings', () => {
const sources = {
command: 'claude',
prefixArgs: [],
@@ -15,12 +15,7 @@ const MODEL_ROW = {
}
describe('codex model catalog probe', () => {
it.each([
[[]],
[['node_modules/@openai/codex/bin/codex.js']],
[['--env-file=work env', '--', 'codex']],
[['-c', 'model_instructions_file="./prompt.md"']]
])(
it.each([[[]]])(
"lists a command line with arguments %j from Orca's folder for every chat",
async (prefixArgs) => {
// The chat's repo never picks the list, so no listing runs in a chat's folder.
@@ -0,0 +1,60 @@
import { isDaemonEndpointGoneError } from '../../protocol/daemon-errors'
import { inspectProcessSignal } from '../../endpoint/identity/daemon-process-inspection'
/**
* Delays between reconnect attempts after a preserved daemon's connection drops; the last repeats.
* Loss needs this many attempts in a row to find the endpoint refused or missing: a timeout or any
* other error cannot tell a busy host from a dead one, so it restarts the count.
*/
export const PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS: readonly number[] = [
500, 2_000, 5_000, 30_000
]
export const PRESERVED_ENDPOINT_LOSS_REQUIRED_GONE = 3
export type PreservedEndpointLossVerdict = 'gone' | 'reachable' | 'abandoned'
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms))
}
/**
* A gone endpoint alone does not prove the process is gone on POSIX: its socket name can be
* unlinked under a live daemon. A Windows pipe exists only while its server handle is open, and
* PID reuse makes a PID probe unsound there, so the missing pipe is the proof.
*/
export function preservedDaemonProcessExited(pid: number | undefined): boolean {
if (process.platform === 'win32') {
return true
}
return pid !== undefined && inspectProcessSignal(pid) === 'missing'
}
/** Decide whether a daemon Orca cannot respawn is gone for good, so its PTYs can end as host loss. */
export async function confirmPreservedEndpointLoss(args: {
connect: () => Promise<void>
shouldContinue: () => boolean
processExited: () => boolean
delaysMs?: readonly number[]
requiredGone?: number
sleep?: (ms: number) => Promise<void>
}): Promise<PreservedEndpointLossVerdict> {
const sleep = args.sleep ?? delay
const delays = args.delaysMs ?? PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS
const requiredGone = args.requiredGone ?? PRESERVED_ENDPOINT_LOSS_REQUIRED_GONE
let gone = 0
for (let attempt = 0; ; attempt++) {
await sleep(delays[Math.min(attempt, delays.length - 1)] ?? 0)
if (!args.shouldContinue()) {
return 'abandoned'
}
try {
await args.connect()
return 'reachable'
} catch (error) {
gone = isDaemonEndpointGoneError(error) && args.processExited() ? gone + 1 : 0
}
if (gone >= requiredGone) {
return 'gone'
}
}
}
@@ -15,6 +15,10 @@ export type DaemonPtyAdapterOptions = {
readRunningWslDistros?: ReadRunningWslDistros
/** Test seam; production reads each distro's boot id through the background-work gate. */
wslBridgeBootIdentity?: WslBridgeBootIdentity
/** Test seam; delays before each reconnect attempt to a dead daemon that cannot respawn. */
preservedEndpointLossProbeDelaysMs?: readonly number[]
/** Test seam; whether a preserved daemon's process is proven gone, given its last pid. */
preservedDaemonExited?: (pid: number | undefined) => boolean
}
export type DaemonRespawnReason =
@@ -12,7 +12,7 @@ import type { DaemonPtyRouterExitEvent } from '../../protocol/daemon-pty-router-
import { logWslPaneDiagnostic } from '../wsl/daemon-wsl-diagnostic-log'
import { classifyWslBridgeExit, WSL_DISTRO_LOSS_EXIT_CODE } from '../wsl/daemon-wsl-bridge-exit'
import { isProvenProcessExit } from '../../../../shared/terminal/pty/lifecycle/terminal-exit-cause'
import { DaemonPtyDaemonRecovery } from './daemon-pty-daemon-recovery'
import { DaemonPtyPreservedHostLoss } from './daemon-pty-preserved-host-loss'
import type { DaemonPtyAdapterOptions } from './daemon-pty-adapter-options'
import type { DaemonEvent } from '../../protocol/daemon-stream-events'
@@ -34,7 +34,7 @@ import type {
import { observeDaemonAsyncIoHealth } from '../../observability/daemon-async-io-telemetry-event'
import { sameEndpointIdentity } from '../../endpoint/identity/daemon-endpoint-incarnation'
export class DaemonPtyAdapter extends DaemonPtyDaemonRecovery implements IPtyProvider {
export class DaemonPtyAdapter extends DaemonPtyPreservedHostLoss implements IPtyProvider {
constructor(opts: DaemonPtyAdapterOptions) {
super(opts)
// Registered after the base listener, which marks the sessions awaiting recovery first.
@@ -0,0 +1,98 @@
import { createPtyExitPayload, emitPtyListeners } from './daemon-pty-listener-emission'
import { DaemonPtyDaemonRecovery } from './daemon-pty-daemon-recovery'
import type { DaemonPtyAdapterOptions } from './daemon-pty-adapter-options'
import {
confirmPreservedEndpointLoss,
PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS,
preservedDaemonProcessExited
} from './daemon-preserved-endpoint-loss'
/**
* A daemon kept from an older Orca version has no respawn. Why (#38432): when it died, nothing
* ended its PTYs, so every pane stayed "connected" on a frozen frame and input went nowhere.
*/
export abstract class DaemonPtyPreservedHostLoss extends DaemonPtyDaemonRecovery {
private readonly preservedEndpointLossProbeDelaysMs: readonly number[]
private readonly preservedDaemonExited: (pid: number | undefined) => boolean
private preservedEndpointLossProbe: Promise<void> | null = null
/** Set once this adapter ended its sessions because its endpoint stayed gone. */
private preservedEndpointLossDeclared = false
constructor(opts: DaemonPtyAdapterOptions) {
super(opts)
this.preservedEndpointLossProbeDelaysMs =
opts.preservedEndpointLossProbeDelaysMs ?? PRESERVED_ENDPOINT_LOSS_PROBE_DELAYS_MS
this.preservedDaemonExited = opts.preservedDaemonExited ?? preservedDaemonProcessExited
}
protected recoverAfterEndpointLoss(): void {
if (this.respawnFn || this.activeSessionIds.size === 0) {
super.recoverAfterEndpointLoss()
return
}
this.confirmPreservedDaemonLoss()
}
// A host proven gone runs no session, so restores (attached or not) route to the current daemon.
async probePtyLiveness(id: string): Promise<boolean | null> {
return this.isProvenGone() ? false : await super.probePtyLiveness(id)
}
listsSession(id: string): Promise<boolean | null> {
return this.isProvenGone() ? Promise.resolve(false) : super.listsSession(id)
}
/** Proven gone and not reconnected since; a later reconnect restores the daemon's own answers. */
private isProvenGone(): boolean {
return this.preservedEndpointLossDeclared && !this.client.isConnected()
}
private confirmPreservedDaemonLoss(): void {
if (this.preservedEndpointLossProbe || this.respawnAdoptionClosed) {
return
}
const stillLost = (): boolean =>
!this.respawnAdoptionClosed && this.activeSessionIds.size > 0 && !this.client.isConnected()
const probe = confirmPreservedEndpointLoss({
connect: () => this.ensureConnected(),
shouldContinue: stillLost,
processExited: () => this.preservedDaemonExited(this.lastAuthenticatedIdentity?.pid),
delaysMs: this.preservedEndpointLossProbeDelaysMs
})
.then((verdict) => {
if (verdict === 'gone' && stillLost()) {
this.endPreservedSessionsAsHostLoss()
}
})
.catch((error) => console.warn('[daemon] Preserved terminal host loss check failed:', error))
.finally(() => {
if (this.preservedEndpointLossProbe === probe) {
this.preservedEndpointLossProbe = null
}
})
this.preservedEndpointLossProbe = probe
}
/** Each PTY ends as host loss with its history kept, so its pane can cold-restore. */
private endPreservedSessionsAsHostLoss(): void {
const ids = [...this.activeSessionIds]
console.warn(
`[daemon] Terminal host v${this.protocolVersion} is gone - ending ${ids.length} session${ids.length === 1 ? '' : 's'} as host loss`
)
this.preservedEndpointLossDeclared = true
const exits = ids.map((id) => {
const incarnationId = this.sessionIncarnations.get(id)
this.hostLossSessionIds.add(id)
this.clearExitedSessionState(id, -1, incarnationId, { closeHistory: false })
return createPtyExitPayload(id, { code: -1, incarnationId, hostLost: true })
})
// State is settled for every session first, so one throwing listener cannot strand the rest.
for (const exit of exits) {
try {
emitPtyListeners(this.exitListeners, (listener) => listener(exit))
} catch (error) {
console.warn('[daemon] Host-loss exit listener failed:', exit.id, error)
}
}
}
}
@@ -0,0 +1,77 @@
import { describe, expect, it } from 'vitest'
import { confirmPreservedEndpointLoss } from '../daemon-preserved-endpoint-loss'
import { DaemonProtocolError } from '../../../protocol/daemon-errors'
function connectError(code: string): Error {
return Object.assign(new Error(`connect ${code}`), { code, syscall: 'connect' })
}
const sleep = async (): Promise<void> => {}
/** Replays connect outcomes in order; once spent, the caller no longer needs a verdict. */
function script(outcomes: (Error | 'ok')[]) {
let index = 0
return {
connect: async () => {
const outcome = outcomes[index++]
if (outcome instanceof Error) {
throw outcome
}
},
shouldContinue: () => index < outcomes.length
}
}
describe('confirmPreservedEndpointLoss', () => {
it('is gone after three refused or missing attempts in a row with the process gone', async () => {
const run = script([
connectError('ECONNREFUSED'),
connectError('ENOENT'),
connectError('ECONNREFUSED')
])
await expect(
confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep })
).resolves.toBe('gone')
})
it('restarts the count on a timeout or other failure instead of reading it as death', async () => {
const run = script([
connectError('ENOENT'),
connectError('ENOENT'),
new DaemonProtocolError('Connection timed out'),
connectError('EPERM'),
connectError('ENOENT'),
connectError('ENOENT')
])
await expect(
confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep })
).resolves.toBe('abandoned')
})
it('keeps checking after an unproven attempt, so a host that dies later is still caught', async () => {
const run = script([
new DaemonProtocolError('Connection timed out'),
connectError('ENOENT'),
connectError('ENOENT'),
connectError('ENOENT'),
connectError('ENOENT')
])
await expect(
confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep })
).resolves.toBe('gone')
})
it('never declares loss while the daemon process may still be alive', async () => {
const run = script(Array.from({ length: 10 }, () => connectError('ECONNREFUSED')))
await expect(
confirmPreservedEndpointLoss({ ...run, processExited: () => false, delaysMs: [1], sleep })
).resolves.toBe('abandoned')
})
it('stops when the host answers again', async () => {
const run = script([connectError('ECONNREFUSED'), 'ok', connectError('ECONNREFUSED')])
await expect(
confirmPreservedEndpointLoss({ ...run, processExited: () => true, delaysMs: [1], sleep })
).resolves.toBe('reachable')
})
})
@@ -0,0 +1,171 @@
// #38432: after an update keeps the previous version's terminal host, that host dying left its
// panes "connected" on a frozen frame. Simulates the upgrade with live sessions on both hosts.
import '../../../pty-subprocess/testing/mock-descendant-sweep'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { DaemonPtyAdapter } from '../daemon-pty-adapter'
import { DaemonPtyRouter } from '../../routing/daemon-pty-router'
import { DaemonServer } from '../../../server/daemon-server'
import { PROTOCOL_VERSION } from '../../../protocol/daemon-protocol-version'
import { getDaemonSocketPath } from '../../../launch/daemon-spawner'
import type { DaemonFileLog } from '../../../observability/daemon-file-log'
import type { DaemonPtyRouterExitEvent } from '../../../protocol/daemon-pty-router-events'
import { createMockSubprocess } from './daemon-pty-adapter-test-harness'
const LEGACY_PROTOCOL = PROTOCOL_VERSION - 1
type ClientInternals = {
handleDisconnect: (generation: number) => void
connectionGeneration: number
isConnected: () => boolean
}
function adapterClient(adapter: DaemonPtyAdapter): ClientInternals {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: reads the adapter's own DaemonClient to drop only its transport, as a broken pipe would.
const internals = adapter as unknown as { client: ClientInternals }
return internals.client
}
describe('a preserved older-version terminal host that dies', () => {
const servers: DaemonServer[] = []
const adapters: DaemonPtyAdapter[] = []
const directories: string[] = []
let router: DaemonPtyRouter | null = null
afterEach(async () => {
router?.dispose()
router = null
for (const adapter of adapters.splice(0)) {
adapter.dispose()
}
await Promise.all(servers.splice(0).map((server) => server.shutdown().catch(() => {})))
for (const directory of directories.splice(0)) {
rmSync(directory, { recursive: true, force: true })
}
})
async function upgradeWithLiveSessions() {
const directory = mkdtempSync(join(tmpdir(), 'daemon-preserved-host-loss-'))
directories.push(directory)
const log: DaemonFileLog = { log: () => {}, close: () => {} }
const legacySocketPath = getDaemonSocketPath(directory, LEGACY_PROTOCOL)
const currentSocketPath = getDaemonSocketPath(directory, PROTOCOL_VERSION)
const legacyTokenPath = join(directory, 'legacy.token')
const currentTokenPath = join(directory, 'current.token')
const legacySubprocesses: ReturnType<typeof createMockSubprocess>[] = []
const currentSubprocesses: ReturnType<typeof createMockSubprocess>[] = []
const legacyServer = new DaemonServer({
socketPath: legacySocketPath,
tokenPath: legacyTokenPath,
protocolVersion: LEGACY_PROTOCOL,
log,
spawnSubprocess: () => {
const subprocess = createMockSubprocess()
legacySubprocesses.push(subprocess)
return subprocess
}
})
const currentServer = new DaemonServer({
socketPath: currentSocketPath,
tokenPath: currentTokenPath,
protocolVersion: PROTOCOL_VERSION,
log,
spawnSubprocess: () => {
const subprocess = createMockSubprocess()
currentSubprocesses.push(subprocess)
return subprocess
}
})
servers.push(legacyServer, currentServer)
await Promise.all([legacyServer.start(), currentServer.start()])
// The previous app version starts two agent panes on its own host, then quits to update.
const oldApp = new DaemonPtyAdapter({
socketPath: legacySocketPath,
tokenPath: legacyTokenPath,
protocolVersion: LEGACY_PROTOCOL
})
adapters.push(oldApp)
const first = await oldApp.spawn({ sessionId: 'agent-1', cols: 80, rows: 24 })
const second = await oldApp.spawn({ sessionId: 'agent-2', cols: 80, rows: 24 })
oldApp.dispose()
// The updated app keeps the old host (no respawn) and starts its own.
const legacy = new DaemonPtyAdapter({
socketPath: legacySocketPath,
tokenPath: legacyTokenPath,
protocolVersion: LEGACY_PROTOCOL,
runtimeDir: directory,
preservedEndpointLossProbeDelaysMs: [5],
// The fixture host shares this test's pid, so its exit is stubbed as proven.
preservedDaemonExited: () => true
})
const current = new DaemonPtyAdapter({
socketPath: currentSocketPath,
tokenPath: currentTokenPath,
protocolVersion: PROTOCOL_VERSION,
runtimeDir: directory
})
adapters.push(legacy, current)
router = new DaemonPtyRouter({ current, legacy: [legacy] })
await router.discoverLegacySessions()
const exits: DaemonPtyRouterExitEvent[] = []
router.onExit((payload) => exits.push(payload))
for (const session of [first, second]) {
await router.spawn({ sessionId: session.id, cols: 80, rows: 24, attachOnly: true })
}
const fresh = await router.spawn({ sessionId: 'new-pane', cols: 80, rows: 24 })
return {
router,
legacy,
legacyServer,
legacySubprocesses,
currentSubprocesses,
exits,
first,
second,
fresh
}
}
it('ends each of its PTYs as host loss, and the panes restore on the current host', async () => {
const run = await upgradeWithLiveSessions()
expect(run.legacySubprocesses).toHaveLength(2)
expect(run.currentSubprocesses).toHaveLength(1)
// The old host dies: its socket stays behind but nothing listens.
await run.legacyServer.shutdown()
await vi.waitFor(() => expect(run.exits).toHaveLength(2), { timeout: 3_000 })
expect(run.exits).toEqual(
expect.arrayContaining([
{ id: run.first.id, code: -1, incarnationId: run.first.incarnationId, hostLost: true },
{ id: run.second.id, code: -1, incarnationId: run.second.incarnationId, hostLost: true }
])
)
// The current host's pane is untouched.
expect(run.exits.some((exit) => exit.id === run.fresh.id)).toBe(false)
expect(run.router.hasPty(run.fresh.id)).toBe(true)
// Restoring the pane must not be refused because the dead host cannot answer.
const restored = await run.router.spawn({ sessionId: run.first.id, cols: 80, rows: 24 })
expect(restored.id).toBe(run.first.id)
expect(run.currentSubprocesses).toHaveLength(2)
})
it('keeps the panes when the host answers again before the loss is proven', async () => {
const run = await upgradeWithLiveSessions()
// Drop only the connection; the host and its PTYs keep running.
const client = adapterClient(run.legacy)
client.handleDisconnect(client.connectionGeneration)
expect(client.isConnected()).toBe(false)
// The first probe reconnects, which settles the check without a verdict of loss.
await vi.waitFor(() => expect(client.isConnected()).toBe(true))
expect(run.exits).toEqual([])
expect(run.router.hasPty(run.first.id)).toBe(true)
expect(run.router.hasPty(run.second.id)).toBe(true)
})
})
@@ -1,167 +0,0 @@
import { EventEmitter } from 'node:events'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const { childSpawnMock, resolveCodexCommandMock, ptySpawnMock } = vi.hoisted(() => ({
childSpawnMock: vi.fn(),
resolveCodexCommandMock: vi.fn(),
ptySpawnMock: vi.fn()
}))
// Keep child-process assertions in this suite; worker transport is covered separately.
vi.mock(
'../../../worker-thread-child-process/worker-thread-child-process',
() =>
import('../../../worker-thread-child-process/worker-thread-child-process-in-process.test-fixtures')
)
vi.mock('node:child_process', () => ({
spawn: childSpawnMock
}))
// Mock recovery so its process-table import does not require real execFile.
vi.mock('../../../codex/history/index/codex-state-db-backfill-recovery', () => ({
startCodexStateDbBackfillRecoveryInBackground: vi.fn()
}))
vi.mock('../../../codex-cli/command', () => ({
resolveCodexCommand: resolveCodexCommandMock
}))
vi.mock('node-pty', () => ({
spawn: ptySpawnMock
}))
vi.mock('./codex-auth-presence', () => ({
probeCodexAuthPresence: vi.fn(() => 'present')
}))
import { fetchCodexRateLimits } from './codex-fetcher'
function makeRpcChild() {
const child = new EventEmitter() as EventEmitter & {
stdout: EventEmitter
stderr: EventEmitter
stdin: EventEmitter & { write: ReturnType<typeof vi.fn>; end: ReturnType<typeof vi.fn> }
kill: ReturnType<typeof vi.fn>
exitCode: number | null
}
child.stdout = new EventEmitter()
child.stderr = new EventEmitter()
// Graceful shutdown must wait for EOF/signal to produce exit, as real app-server does.
const exitNow = (): void => {
child.exitCode = 0
child.emit('exit', 0, null)
}
child.stdin = Object.assign(new EventEmitter(), { write: vi.fn(), end: vi.fn(exitNow) })
child.exitCode = null
child.kill = vi.fn(() => {
exitNow()
return true
})
return child
}
describe('fetchCodexRateLimits auth errors', () => {
beforeEach(() => {
vi.useFakeTimers()
vi.clearAllMocks()
resolveCodexCommandMock.mockReturnValue('codex')
vi.stubGlobal('fetch', vi.fn())
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('returns Codex RPC auth refresh errors without masking them behind a fallback', async () => {
const rpcChild = makeRpcChild()
const authError =
'Your access token could not be refreshed because your refresh token was already used. Please log out and sign in again.'
childSpawnMock.mockReturnValue(rpcChild)
rpcChild.stdin.write.mockImplementation((line: string) => {
const msg = JSON.parse(line) as { id?: number; method?: string }
if (msg.method === 'initialize') {
setTimeout(() => {
rpcChild.stdout.emit(
'data',
Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`)
)
}, 0)
}
if (msg.method === 'account/rateLimits/read') {
setTimeout(() => {
rpcChild.stdout.emit(
'data',
Buffer.from(
`${JSON.stringify({
jsonrpc: '2.0',
id: msg.id,
error: { code: -32000, message: authError }
})}\n`
)
)
}, 0)
}
})
const resultPromise = fetchCodexRateLimits()
await vi.advanceTimersByTimeAsync(1)
await vi.advanceTimersByTimeAsync(1)
await expect(resultPromise).resolves.toMatchObject({
provider: 'codex',
session: null,
weekly: null,
status: 'error',
error: authError
})
expect(fetch).not.toHaveBeenCalled()
expect(ptySpawnMock).not.toHaveBeenCalled()
})
it('returns the app-server chatgpt-auth-required error without falling back', async () => {
const rpcChild = makeRpcChild()
const authError = 'chatgpt authentication required to read rate limits'
childSpawnMock.mockReturnValue(rpcChild)
rpcChild.stdin.write.mockImplementation((line: string) => {
const msg = JSON.parse(line) as { id?: number; method?: string }
if (msg.method === 'initialize') {
setTimeout(() => {
rpcChild.stdout.emit(
'data',
Buffer.from(`${JSON.stringify({ jsonrpc: '2.0', id: msg.id, result: {} })}\n`)
)
}, 0)
}
if (msg.method === 'account/rateLimits/read') {
setTimeout(() => {
rpcChild.stdout.emit(
'data',
Buffer.from(
`${JSON.stringify({
jsonrpc: '2.0',
id: msg.id,
error: { code: -32600, message: authError }
})}\n`
)
)
}, 0)
}
})
const resultPromise = fetchCodexRateLimits()
await vi.advanceTimersByTimeAsync(1)
await vi.advanceTimersByTimeAsync(1)
await expect(resultPromise).resolves.toMatchObject({
provider: 'codex',
session: null,
weekly: null,
status: 'error',
error: authError
})
expect(fetch).not.toHaveBeenCalled()
expect(ptySpawnMock).not.toHaveBeenCalled()
})
})
@@ -1,206 +0,0 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as RunProcess from '@orca/process-host'
const { ptySpawnMock, resolveCodexCommandMock, stubScript } = vi.hoisted(() => ({
stubScript: { path: '' },
ptySpawnMock: vi.fn(),
resolveCodexCommandMock: vi.fn()
}))
// Run the Node fixture through the real process chokepoint; worker transport has separate coverage.
vi.mock(
'../../../worker-thread-child-process/worker-thread-child-process',
() =>
import('../../../worker-thread-child-process/worker-thread-child-process-in-process.test-fixtures')
)
vi.mock('@orca/process-host', async (importOriginal) => {
const actual = await importOriginal<typeof RunProcess>()
return {
...actual,
spawnProcess: (spec: Parameters<typeof actual.spawnProcess>[0]) =>
actual.spawnProcess({
...spec,
program: process.execPath,
args: [stubScript.path, ...(spec.args ?? [])]
})
}
})
vi.mock('../../../codex-cli/command', () => ({
resolveCodexCommand: resolveCodexCommandMock
}))
vi.mock('node-pty', () => ({
spawn: ptySpawnMock
}))
vi.mock('./codex-auth-presence', () => ({
probeCodexAuthPresence: vi.fn(() => 'present')
}))
vi.mock('../../../codex/history/index/codex-state-db', () => ({
isCodexStateDbBackfillPending: vi.fn(() => false)
}))
vi.mock('../../../codex/history/index/codex-state-db-backfill-recovery', () => ({
startCodexStateDbBackfillRecoveryInBackground: vi.fn(() => Promise.resolve(null))
}))
import { fetchCodexRateLimits } from './codex-fetcher'
const STUB_CODEX_SOURCE = `
const expectedArgs = [
'-c',
'approval_policy=never',
'-c',
'features.plugins=false',
'-s',
'read-only',
'-a',
'never',
'app-server'
]
if (JSON.stringify(process.argv.slice(2)) !== JSON.stringify(expectedArgs)) {
process.stderr.write(
"error: invalid value 'untrusted' for '--ask-for-approval <APPROVAL_POLICY>'\\n" +
' [possible values: on-request, never]\\n'
)
process.exit(2)
}
if (process.env.CODEX_HOME !== process.env.ORCA_EXPECTED_CODEX_HOME) {
process.stderr.write('managed CODEX_HOME was not preserved\\n')
process.exit(3)
}
if (process.env.ORCA_EXPECTED_PROXY_ENV) {
for (const [key, value] of Object.entries(JSON.parse(process.env.ORCA_EXPECTED_PROXY_ENV))) {
if (process.env[key] !== value) {
process.stderr.write('probe proxy environment mismatch: ' + key + '\\n')
process.exit(4)
}
}
}
let buffer = ''
function send(message) {
process.stdout.write(JSON.stringify(message) + '\\n')
}
process.stdin.setEncoding('utf8')
process.stdin.on('data', (chunk) => {
buffer += chunk
let newlineIndex
while ((newlineIndex = buffer.indexOf('\\n')) !== -1) {
const line = buffer.slice(0, newlineIndex).trim()
buffer = buffer.slice(newlineIndex + 1)
if (!line) continue
const message = JSON.parse(line)
if (message.method === 'initialize') {
send({ id: message.id, result: { userAgent: 'codex-contract/0.149.0' } })
continue
}
if (message.method === 'account/rateLimits/read') {
send({
id: message.id,
result: {
rateLimits: {
primary: { usedPercent: 17, windowDurationMins: 300 },
secondary: { usedPercent: 29, windowDurationMins: 10080 }
}
}
})
}
}
})
process.stdin.on('end', () => process.exit(0))
`
let tempRoot: string
let stubPath: string
let previousExpectedHome: string | undefined
describe('Codex rate-limit process contract', () => {
beforeEach(() => {
tempRoot = mkdtempSync(join(tmpdir(), 'orca-codex-rate-limit-contract-'))
stubPath = join(tempRoot, 'codex-contract.cjs')
writeFileSync(stubPath, STUB_CODEX_SOURCE)
previousExpectedHome = process.env.ORCA_EXPECTED_CODEX_HOME
process.env.ORCA_EXPECTED_CODEX_HOME = join(tempRoot, 'managed-codex-home')
resolveCodexCommandMock.mockReturnValue('codex')
stubScript.path = stubPath
})
afterEach(() => {
vi.unstubAllEnvs()
if (previousExpectedHome === undefined) {
delete process.env.ORCA_EXPECTED_CODEX_HOME
} else {
process.env.ORCA_EXPECTED_CODEX_HOME = previousExpectedHome
}
rmSync(tempRoot, { recursive: true, force: true })
vi.clearAllMocks()
})
it('starts a read-only non-interactive app-server with the managed home', async () => {
await expect(
fetchCodexRateLimits({
codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME
})
).resolves.toMatchObject({
provider: 'codex',
session: { usedPercent: 17, windowMinutes: 300 },
weekly: { usedPercent: 29, windowMinutes: 10080 },
status: 'ok',
error: null
})
expect(ptySpawnMock).not.toHaveBeenCalled()
})
it.each(['localhost;*.fixture.invalid', ''])(
'passes configured proxy and bypass %j to the actual probe',
async (bypassRules) => {
const proxy = 'http://proxy.fixture.invalid:8080'
const expected = {
HTTP_PROXY: proxy,
HTTPS_PROXY: proxy,
ALL_PROXY: proxy,
http_proxy: proxy,
https_proxy: proxy,
all_proxy: proxy,
NO_PROXY: bypassRules.replaceAll(';', ','),
no_proxy: bypassRules.replaceAll(';', ',')
}
vi.stubEnv('NO_PROXY', 'inherited.invalid')
vi.stubEnv('no_proxy', 'inherited.invalid')
vi.stubEnv('ORCA_EXPECTED_PROXY_ENV', JSON.stringify(expected))
await expect(
fetchCodexRateLimits({
codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME,
networkProxySettings: { httpProxyUrl: proxy, httpProxyBypassRules: bypassRules }
})
).resolves.toMatchObject({ status: 'ok', session: { usedPercent: 17 } })
expect(process.env.NO_PROXY).toBe('inherited.invalid')
}
)
it.each([undefined, { httpProxyUrl: '' }, { httpProxyUrl: 'file:///invalid-proxy' }])(
'preserves inherited proxy settings when app settings are unset or invalid: %j',
async (networkProxySettings) => {
const inherited = {
HTTPS_PROXY: 'http://inherited.fixture.invalid:8080',
NO_PROXY: 'fixture.invalid'
}
for (const [key, value] of Object.entries(inherited)) {
vi.stubEnv(key, value)
}
vi.stubEnv('ORCA_EXPECTED_PROXY_ENV', JSON.stringify(inherited))
await expect(
fetchCodexRateLimits({
codexHomePath: process.env.ORCA_EXPECTED_CODEX_HOME,
networkProxySettings
})
).resolves.toMatchObject({ status: 'ok', session: { usedPercent: 17 } })
}
)
})
@@ -86,29 +86,6 @@ describe('Codex RPC exit diagnostics', () => {
vi.clearAllMocks()
})
it('names the exit code and what the child reported', async () => {
const result = await runStub(
"error: invalid value 'untrusted' for '--ask-for-approval <APPROVAL_POLICY>'\n" +
" [possible values: on-request, never]\n\nFor more information, try '--help'.\n",
2
)
expect(result.error).toContain('Codex RPC process exited (exit code 2)')
expect(result.error).toContain("invalid value 'untrusted'")
expect(result.error).toContain("try '--help'")
})
it('classifies a dead refresh token so the re-auth warning fires', async () => {
const result = await runStub(
'2026-08-20T18:04:11.221Z INFO codex_core::auth: refreshing ChatGPT tokens\n' +
'ERROR: The ChatGPT access token could not be refreshed; please sign in again.\n',
1
)
expect(result.error).toBe('Your ChatGPT session could not be refreshed. Please sign in again.')
expect(isCodexAuthError(result.error)).toBe(true)
})
it('keeps the re-auth phrase that path redaction would swallow', async () => {
const result = await runStub(
`ERROR: /Users/haris/.codex/auth.json is stale — please sign in again.\n`,
@@ -2,7 +2,6 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as WslTranscriptFsAccess from '../../../native-chat/wsl-transcript-fs-access'
import Database from '../../../sqlite/sync-database'
import { detectOpenCodeCredentialBackend } from '../../../opencode/opencode-credential-backend'
import { resolveOpenCodeGoApiKey } from './opencode-go-api-key-source'
@@ -21,17 +20,6 @@ const ENVIRONMENT_KEYS = [
'OPENCODE_AUTH_CONTENT'
] as const
// Inject listing failures that host filesystems cannot produce portably.
const readdirFailure = vi.hoisted((): { error: unknown } => ({ error: null }))
vi.mock('../../../native-chat/wsl-transcript-fs-access', async (importOriginal) => {
const actual = await importOriginal<typeof WslTranscriptFsAccess>()
return {
...actual,
wslGatedReaddir: (...args: Parameters<typeof actual.wslGatedReaddir>) =>
readdirFailure.error ? Promise.reject(readdirFailure.error) : actual.wslGatedReaddir(...args)
}
})
describe('resolveOpenCodeGoApiKey', () => {
let dataHome: string
let originalEnvironment: Partial<Record<(typeof ENVIRONMENT_KEYS)[number], string>>
@@ -74,7 +62,6 @@ describe('resolveOpenCodeGoApiKey', () => {
})
afterEach(() => {
readdirFailure.error = null
for (const key of ENVIRONMENT_KEYS) {
const value = originalEnvironment[key]
if (value === undefined) {
@@ -126,84 +113,4 @@ describe('resolveOpenCodeGoApiKey', () => {
tier: 'opencode-auth-file'
})
})
it('does not fall back to the auth file when valid v1 inline auth omits Go', async () => {
writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } })
process.env.OPENCODE_AUTH_CONTENT = '{}'
process.env.OPENCODE_API_KEY = ENVIRONMENT_KEY
await expect(resolveOpenCodeGoApiKey({ backend: 'v1' })).resolves.toEqual({
status: 'found',
key: ENVIRONMENT_KEY,
tier: 'environment'
})
})
it.each([undefined, '', ' \t\n '])(
'does not borrow the host key when an unknown selected backend has environment key %j',
async (key) => {
vi.mocked(detectOpenCodeCredentialBackend).mockResolvedValue(null)
process.env.OPENCODE_API_KEY = ENVIRONMENT_KEY
const environment: NodeJS.ProcessEnv = { OPENCODE_API_KEY: key }
await expect(resolveOpenCodeGoApiKey({ environment })).resolves.toEqual({ status: 'missing' })
expect(detectOpenCodeCredentialBackend).toHaveBeenCalledWith(environment, undefined)
}
)
it('propagates unreadable selected context instead of reading host credentials', async () => {
writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } })
const input = {}
Object.defineProperty(input, 'environment', {
get: () => {
throw new Error('Selected profile metadata is unreadable')
}
})
await expect(resolveOpenCodeGoApiKey(input)).rejects.toThrow(
'Selected profile metadata is unreadable'
)
})
it.each(['v1', 'v2'] as const)(
'keeps System and selected data roots isolated for %s',
async (backend) => {
writeAuthFile({ 'opencode-go': { type: 'api', key: AUTH_FILE_KEY } })
const system = { XDG_DATA_HOME: dataHome, OPENCODE_DB: ':memory:' }
const selectedDataHome = join(dataHome, 'selected')
mkdirSync(join(selectedDataHome, 'opencode'), { recursive: true })
writeFileSync(
join(selectedDataHome, 'opencode', 'auth.json'),
JSON.stringify({
'opencode-go': { type: 'api', key: 'selected-auth-placeholder' }
})
)
const { path } = writeCredentialDatabase([
{
value: JSON.stringify({ type: 'key', key: 'selected-table-placeholder' }),
active: 1,
created: 1
}
])
const selected = { XDG_DATA_HOME: selectedDataHome, OPENCODE_DB: path }
const inherited = { ...process.env }
const first = await resolveOpenCodeGoApiKey({ environment: system, backend })
const managed = await resolveOpenCodeGoApiKey({ environment: selected, backend })
const restored = await resolveOpenCodeGoApiKey({ environment: system, backend })
expect(first).toEqual({ status: 'found', key: AUTH_FILE_KEY, tier: 'opencode-auth-file' })
expect(managed).toEqual(
backend === 'v1'
? { status: 'found', key: 'selected-auth-placeholder', tier: 'opencode-auth-file' }
: {
status: 'found',
key: 'selected-table-placeholder',
tier: 'opencode-credential-database'
}
)
expect(restored).toEqual(first)
expect(process.env).toEqual(inherited)
}
)
})
@@ -1,81 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
isOpenCodeGoExplicitNoAccessPayload,
parseOpenCodeGoBillingStatusPayload,
parseOpenCodeGoStatusPayload,
parseOpenCodeGoUsageApiPayload
} from './opencode-go-status-parsing'
const ISSUE_PAYLOAD = {
access: {
meters: {
fiveHour: {
resetsAt: '2026-09-18T12:42:04.962Z',
limitMicroCents: '1200000000',
usedMicroCents: '121745383'
},
week: {
resetsAt: '2026-09-21T00:00:00.000Z',
limitMicroCents: '3000000000',
usedMicroCents: '121745383'
},
month: {
limitMicroCents: '6000000000',
usedMicroCents: '121745383'
}
}
}
}
describe('parseOpenCodeGoStatusPayload', () => {
it('maps fiveHour/week/month meters into session/weekly/monthly windows', () => {
const parsed = parseOpenCodeGoStatusPayload(JSON.stringify(ISSUE_PAYLOAD))
expect(parsed).not.toBeNull()
expect(parsed?.session).toEqual({
usedPercent: (121745383 / 1_200_000_000) * 100,
windowMinutes: 300,
resetsAt: Date.parse('2026-09-18T12:42:04.962Z'),
resetDescription: null
})
expect(parsed?.weekly).toEqual({
usedPercent: (121745383 / 3_000_000_000) * 100,
windowMinutes: 10_080,
resetsAt: Date.parse('2026-09-21T00:00:00.000Z'),
resetDescription: null
})
expect(parsed?.monthly).toEqual({
usedPercent: (121745383 / 6_000_000_000) * 100,
windowMinutes: 43_200,
resetsAt: null,
resetDescription: null
})
})
it('caps usedPercent at 100 and floors at 0', () => {
const parsed = parseOpenCodeGoStatusPayload(
JSON.stringify({
access: {
meters: {
fiveHour: {
resetsAt: '2026-09-18T12:42:04.962Z',
limitMicroCents: '100',
usedMicroCents: '150'
},
week: {
resetsAt: '2026-09-21T00:00:00.000Z',
limitMicroCents: '100',
usedMicroCents: '-5'
}
}
}
})
)
expect(parsed?.session?.usedPercent).toBe(100)
expect(parsed?.weekly?.usedPercent).toBe(0)
})
})
import { parseOpenCodeGoBillingStatusPayload } from './opencode-go-status-parsing'
describe('parseOpenCodeGoBillingStatusPayload', () => {
it('maps the verified PAYG micro-cent string into USD major units', () => {
@@ -89,76 +13,4 @@ describe('parseOpenCodeGoBillingStatusPayload', () => {
)
).toBe(27.86781005)
})
it('preserves zero and negative balances', () => {
expect(
parseOpenCodeGoBillingStatusPayload(
JSON.stringify({
billingMode: 'prepaid',
mode: 'pay-as-you-go',
balanceMicroCents: '0'
})
)
).toBe(0)
expect(
parseOpenCodeGoBillingStatusPayload(
JSON.stringify({
billingMode: 'prepaid',
mode: 'pay-as-you-go',
balanceMicroCents: '-125000000'
})
)
).toBe(-1.25)
})
it.each([
{ billingMode: 'credit', mode: 'pay-as-you-go', balanceMicroCents: '100000000' },
{ billingMode: 'seat', mode: 'pay-as-you-go', balanceMicroCents: '100000000' },
{ billingMode: 'prepaid', mode: 'invoiceable', balanceMicroCents: '100000000' },
{ billingMode: 'prepaid', mode: 'pay-as-you-go', balanceMicroCents: 100000000 },
{ billingMode: 'prepaid', mode: 'pay-as-you-go', balanceMicroCents: '1.5' },
{
billingMode: 'prepaid',
mode: 'pay-as-you-go',
balanceMicroCents: '9007199254740992'
}
])('rejects unsupported or unsafe billing payloads: $billingMode/$mode', (payload) => {
expect(parseOpenCodeGoBillingStatusPayload(JSON.stringify(payload))).toBeNull()
})
})
describe('isOpenCodeGoExplicitNoAccessPayload', () => {
it('accepts only explicit JSON null or access:null without an error verdict', () => {
expect(isOpenCodeGoExplicitNoAccessPayload('null')).toBe(true)
expect(isOpenCodeGoExplicitNoAccessPayload('{"access":null}')).toBe(true)
expect(
isOpenCodeGoExplicitNoAccessPayload('{"access":null,"error":{"type":"AuthError"}}')
).toBe(false)
expect(isOpenCodeGoExplicitNoAccessPayload('{"access":{}}')).toBe(false)
expect(isOpenCodeGoExplicitNoAccessPayload('{}')).toBe(false)
expect(isOpenCodeGoExplicitNoAccessPayload('<html></html>')).toBe(false)
expect(isOpenCodeGoExplicitNoAccessPayload('{not json')).toBe(false)
})
})
describe('parseOpenCodeGoUsageApiPayload', () => {
it('clamps an out-of-range percent and tolerates a missing resetsAt', () => {
const parsed = parseOpenCodeGoUsageApiPayload(
JSON.stringify({
usage: {
rolling: { status: 'rate-limited', percent: 140 },
weekly: { status: 'ok', percent: -5, resetsAt: 'not a date' }
}
})
)
expect(parsed?.session).toEqual({
usedPercent: 100,
windowMinutes: 300,
resetsAt: null,
resetDescription: null
})
expect(parsed?.weekly.usedPercent).toBe(0)
expect(parsed?.monthly).toBeNull()
})
})
@@ -77,66 +77,6 @@ describe('RateLimitService', () => {
resetRateLimitProviderMocks()
})
it('settles without applying a result when the managed home becomes unavailable mid-fetch', async () => {
const service = new RateLimitService()
const resolver = vi
.fn()
.mockReturnValueOnce({ kind: 'ready', codexHomePath: '/tmp/codex-home' })
.mockReturnValue({ kind: 'skip' })
service.setCodexHomePathResolver(resolver)
vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 20, Date.now()))
await service.refreshForCodexAccountChange(null, { runtime: 'host' })
expect(resolver).toHaveBeenCalledTimes(2)
expect(fetchCodexRateLimits).toHaveBeenCalledOnce()
expect(service.getState().codex).toBeNull()
})
it('returns a refreshed scoped state without overwriting a target selected during reset', async () => {
const service = new RateLimitService()
const idempotencyKey = '22222222-2222-4222-8222-222222222222'
const consume = vi.mocked(consumeCodexRateLimitResetCredit)
let resolveConsume: ((outcome: 'reset') => void) | undefined
consume.mockImplementationOnce(
() =>
new Promise((resolve) => {
resolveConsume = resolve
})
)
vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 0, Date.now()))
service.setCodexHomePathResolver(() => ({ kind: 'ready', codexHomePath: '/tmp/new-selection' }))
const pending = service.consumeCodexRateLimitResetCredit({
idempotencyKey,
target: { runtime: 'host', wslDistro: null },
codexHomePath: '/tmp/approved-selection'
})
await vi.waitFor(() => expect(consume).toHaveBeenCalledOnce())
service.setCodexFetchTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' })
resolveConsume?.('reset')
await expect(pending).resolves.toMatchObject({
outcome: 'reset',
state: {
codexTarget: { runtime: 'host', wslDistro: null },
codex: { session: { usedPercent: 0 } }
}
})
expect(consume).toHaveBeenCalledWith({
codexHomePath: '/tmp/approved-selection',
idempotencyKey
})
expect(fetchCodexRateLimits).toHaveBeenCalledWith(
expect.objectContaining({
codexHomePath: '/tmp/approved-selection',
signal: expect.any(AbortSignal)
})
)
expect(service.getState().codexTarget).toEqual({ runtime: 'wsl', wslDistro: 'Ubuntu' })
expect(service.getState().codex).toBeNull()
})
it('keeps the reset result scoped when the active target changes during its refresh', async () => {
const service = new RateLimitService()
const idempotencyKey = '33333333-3333-4333-8333-333333333333'
@@ -201,120 +141,4 @@ describe('RateLimitService', () => {
expect(service.getState().codex?.session?.usedPercent).toBe(0)
})
it('does not fetch host Codex usage when WSL home resolution fails', async () => {
const service = new RateLimitService()
const resolver = vi.fn(() => ({ kind: 'ready' as const, codexHomePath: null }))
service.setCodexHomePathResolver(resolver)
service.setCodexFetchTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' })
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce(
okProvider('claude', 10, Date.now())
)
await service.refresh()
expect(resolver).toHaveBeenCalledWith({ runtime: 'wsl', wslDistro: 'Ubuntu' })
expect(fetchCodexRateLimits).not.toHaveBeenCalled()
expect(service.getState().codex).toMatchObject({
provider: 'codex',
status: 'error',
error: 'WSL Codex home unavailable for Ubuntu'
})
})
it('does not cache host Codex usage under an outgoing WSL account', async () => {
const service = new RateLimitService()
const wslCodexHome =
'\\\\wsl.localhost\\Ubuntu\\home\\jin\\.local\\share\\orca\\codex-accounts\\a\\home'
const hostCodexHome = 'C:\\Users\\jin\\.orca\\codex-accounts\\host\\home'
service.setCodexHomePathResolver((target) => ({
kind: 'ready',
codexHomePath: target?.runtime === 'wsl' ? wslCodexHome : hostCodexHome
}))
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce(
okProvider('claude', 10, Date.now())
)
vi.mocked(fetchCodexRateLimits)
.mockResolvedValueOnce(okProvider('codex', 20, Date.now()))
.mockResolvedValueOnce(okProvider('codex', 40, Date.now()))
await service.refresh()
await service.refreshForCodexAccountChange('wsl-account-1', {
runtime: 'wsl',
wslDistro: 'Ubuntu'
})
expect(service.getState().inactiveCodexAccounts).not.toEqual(
expect.arrayContaining([expect.objectContaining({ accountId: 'wsl-account-1' })])
)
})
it('does not cache host Claude usage under an outgoing WSL account', async () => {
const service = new RateLimitService()
service.setInactiveClaudeAccountsResolver(() => [{ id: 'wsl-account-1' }])
service.setClaudeAuthPreparationResolver(async (target) => ({
configDir:
target?.runtime === 'wsl'
? '\\\\wsl.localhost\\Ubuntu\\home\\jin\\.claude'
: 'C:\\Users\\jin\\.claude',
runtime: target?.runtime ?? 'host',
wslDistro: target?.wslDistro ?? null,
wslLinuxConfigDir: target?.runtime === 'wsl' ? '/home/jin/.claude' : null,
envPatch: {},
provenance: target?.runtime === 'wsl' ? 'managed:wsl-account-1:wsl:Ubuntu' : 'system'
}))
vi.mocked(fetchActiveClaudeRateLimits)
.mockResolvedValueOnce(okProvider('claude', 20, Date.now()))
.mockResolvedValueOnce(okProvider('claude', 40, Date.now()))
vi.mocked(fetchCodexRateLimits).mockResolvedValueOnce(okProvider('codex', 20, Date.now()))
await service.refresh()
await service.refreshForClaudeAccountChange('wsl-account-1', {
runtime: 'wsl',
wslDistro: 'Ubuntu'
})
expect(fetchActiveClaudeRateLimits).toHaveBeenLastCalledWith(
expect.objectContaining({ allowPtyFallback: true, allowUsagePanelSupplement: true })
)
expect(service.getState().inactiveClaudeAccounts).not.toEqual(
expect.arrayContaining([expect.objectContaining({ accountId: 'wsl-account-1' })])
)
})
// Regression: the Codex home resolver is async, and a reset never waits on isFetching.
it('does not apply a stale full-refresh cycle codex result over a newer reset', async () => {
const service = new RateLimitService()
const staleHome = deferred<{ kind: 'ready'; codexHomePath: string | null }>()
const resolver = vi
.fn()
.mockReturnValueOnce(staleHome.promise)
.mockResolvedValue({ kind: 'ready', codexHomePath: '/tmp/approved-selection' })
service.setCodexHomePathResolver(resolver)
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 10, Date.now()))
vi.mocked(fetchCodexRateLimits)
.mockResolvedValueOnce(okProvider('codex', 0, Date.now()))
.mockResolvedValueOnce(okProvider('codex', 100, Date.now()))
vi.mocked(consumeCodexRateLimitResetCredit).mockResolvedValueOnce('reset')
const staleRefresh = service.refresh()
await vi.waitFor(() => expect(resolver).toHaveBeenCalledTimes(1))
await expect(
service.consumeCodexRateLimitResetCredit({
idempotencyKey: '55555555-5555-4555-8555-555555555555',
target: { runtime: 'host', wslDistro: null },
codexHomePath: '/tmp/approved-selection'
})
).resolves.toMatchObject({ outcome: 'reset' })
staleHome.resolve({ kind: 'ready', codexHomePath: '/tmp/approved-selection' })
await staleRefresh
expect(service.getState().codex?.session?.usedPercent).not.toBe(100)
})
})
@@ -10,13 +10,6 @@ import {
resetRateLimitProviderMocks
} from './rate-limit-service-test-harness'
function inactiveCodexAccount(id: string, managedHomePath: string) {
return {
id,
resolveHome: () => ({ kind: 'ready' as const, managedHomePath })
}
}
vi.mock('../providers/claude/claude-active-usage-fetch', () => ({
fetchActiveClaudeRateLimits: vi.fn()
}))
@@ -90,101 +83,6 @@ describe('RateLimitService', () => {
vi.useRealTimers()
})
it('keeps sibling inactive Codex preview fetches alive when one account is evicted', async () => {
const service = new RateLimitService()
const accountFetch = deferred<ProviderRateLimits>()
let inactiveAccounts = [
inactiveCodexAccount('account-a', '/tmp/account-a/home'),
inactiveCodexAccount('account-b', '/tmp/account-b/home')
]
service.setInactiveCodexAccountsResolver(() => inactiveAccounts)
vi.mocked(fetchCodexRateLimits).mockReturnValueOnce(accountFetch.promise)
const fetchOnOpen = service.fetchInactiveCodexAccountsOnOpen()
await Promise.resolve()
expect(service.getState().inactiveCodexAccounts).toEqual([
{ accountId: 'account-a', rateLimits: null, updatedAt: 0, isFetching: true }
])
inactiveAccounts = [inactiveCodexAccount('account-a', '/tmp/account-a/home')]
service.evictInactiveCodexCache('account-b')
accountFetch.resolve(okProvider('codex', 64, Date.now()))
await fetchOnOpen
expect(fetchCodexRateLimits).toHaveBeenCalledTimes(1)
expect(service.getState().inactiveCodexAccounts).toEqual([
{
accountId: 'account-a',
rateLimits: expect.objectContaining({
provider: 'codex',
session: expect.objectContaining({ usedPercent: 64 })
}),
updatedAt: expect.any(Number),
isFetching: false
}
])
})
it('does not recache an inactive Codex account that becomes active during fetch-on-open', async () => {
const service = new RateLimitService()
const accountFetch = deferred<ProviderRateLimits>()
let inactiveAccounts = [inactiveCodexAccount('account-b', '/tmp/account-b/home')]
service.setInactiveCodexAccountsResolver(() => inactiveAccounts)
service.setCodexHomePathResolver(() => ({
kind: 'ready',
codexHomePath: '/tmp/account-b/home'
}))
vi.mocked(fetchCodexRateLimits)
.mockReturnValueOnce(accountFetch.promise)
.mockResolvedValueOnce(okProvider('codex', 7, Date.now()))
const fetchOnOpen = service.fetchInactiveCodexAccountsOnOpen()
await Promise.resolve()
expect(service.getState().inactiveCodexAccounts).toEqual([
{ accountId: 'account-b', rateLimits: null, updatedAt: 0, isFetching: true }
])
inactiveAccounts = []
await service.refreshForCodexAccountChange('account-a')
accountFetch.resolve(okProvider('codex', 42, Date.now()))
await fetchOnOpen
expect(service.getState().inactiveCodexAccounts).toEqual([])
})
it('does not recache an inactive Claude account removed during fetch-on-open', async () => {
const service = new RateLimitService()
const accountFetch = deferred<ProviderRateLimits>()
let inactiveAccounts = [{ id: 'account-1' }]
service.setInactiveClaudeAccountsResolver(() => inactiveAccounts)
service.setClaudeAuthPreparationResolver(async () => ({
configDir: '/tmp/.claude',
envPatch: {},
provenance: 'system'
}))
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 7))
await service.refresh()
vi.mocked(fetchInactiveClaudeAccountUsage).mockReturnValueOnce(accountFetch.promise)
const fetchOnOpen = service.fetchInactiveClaudeAccountsOnOpen()
await Promise.resolve()
expect(service.getState().inactiveClaudeAccounts).toEqual([
{ accountId: 'account-1', rateLimits: null, updatedAt: 0, isFetching: true }
])
service.evictInactiveClaudeCache('account-1')
inactiveAccounts = [{ id: 'account-1' }]
await service.refreshForClaudeAccountChange('account-1')
expect(service.getState().inactiveClaudeAccounts[0]?.accountId).toBe('account-1')
inactiveAccounts = []
service.evictInactiveClaudeCache('account-1')
accountFetch.resolve(okProvider('claude', 42))
await fetchOnOpen
expect(service.getState().inactiveClaudeAccounts).toEqual([])
})
it('does not overwrite inactive Claude cache from a stale same-id fetch', async () => {
const service = new RateLimitService()
const accountFetch = deferred<ProviderRateLimits>()
@@ -1,279 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ProviderRateLimits } from '../../../shared/rate-limit-types'
import { RateLimitService } from './rate-limit-service'
import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch'
import {
deferred,
errorProvider,
flushMicrotasks,
mockFreshBackgroundProviderFetches,
okProvider,
resetRateLimitProviderMocks
} from './rate-limit-service-test-harness'
class ObservedRateLimitService extends RateLimitService {
get claudeCheckCompletedAt(): number | null {
return this.lastClaudeCheckCompletedAt
}
get activeRefreshPlan() {
return this.getActiveWindowRefreshPlan(Date.now())
}
}
const profileRouter = vi.hoisted((): { userConfigDir?: string } => ({}))
vi.mock('../../claude-accounts/claude-profile-installed-router', () => ({
getClaudeProfileRouter: () =>
profileRouter.userConfigDir ? { userConfigDir: () => profileRouter.userConfigDir } : undefined
}))
vi.mock('../providers/claude/claude-active-usage-fetch', () => ({
fetchActiveClaudeRateLimits: vi.fn()
}))
vi.mock('../providers/claude/claude-managed-account-usage', () => ({
fetchInactiveClaudeAccountUsage: vi.fn()
}))
vi.mock('../providers/codex/codex-fetcher', () => ({
consumeCodexRateLimitResetCredit: vi.fn(),
fetchCodexRateLimits: vi.fn()
}))
vi.mock('../providers/gemini/gemini-usage-fetcher', () => ({
fetchGeminiRateLimits: vi.fn()
}))
vi.mock('../providers/kimi/kimi-fetcher', () => ({
fetchKimiRateLimits: vi.fn()
}))
vi.mock('../providers/opencode-go/opencode-go-usage-source-selection', () => ({
fetchOpenCodeGoUsage: vi.fn()
}))
vi.mock('../providers/zcode/zcode-usage-fetcher', () => ({
fetchZcodeRateLimits: vi.fn()
}))
vi.mock('../providers/muse/muse-usage-fetcher', () => ({
fetchMuseRateLimits: vi.fn()
}))
vi.mock('../providers/antigravity/antigravity-usage-fetcher', () => ({
fetchAntigravityRateLimits: vi.fn()
}))
vi.mock('../providers/minimax/minimax-fetcher', () => ({
fetchMiniMaxRateLimits: vi.fn()
}))
vi.mock('../providers/grok/grok-fetcher', () => ({
fetchGrokRateLimits: vi.fn()
}))
vi.mock('../providers/cursor/cursor-fetcher', () => ({
fetchCursorRateLimits: vi.fn()
}))
vi.mock('../providers/cursor/cursor-auth', () => ({
readCursorAuthSession: vi.fn()
}))
vi.mock('../providers/grok/grok-auth', () => ({
readGrokAuthSession: vi.fn(() => ({ status: 'missing' }))
}))
vi.mock('../../minimax/minimax-cookie-store', () => ({
hasMiniMaxSessionCookie: vi.fn(() => false)
}))
describe('RateLimitService', () => {
beforeEach(() => {
resetRateLimitProviderMocks()
})
it('drops statusline posts before attribution is known or from a mismatched config dir', async () => {
vi.useFakeTimers()
try {
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue(okProvider('claude', 18))
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
// No cycle has established selected-account attribution yet.
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour: { used_percentage: 50 },
sevenDay: null
})
expect(service.getState().claude).toBeNull()
await service.refresh()
expect(service.getState().claude?.session?.usedPercent).toBe(18)
service.ingestLiveClaudeRateLimits({
configDir: '/some/managed/dir',
fiveHour: { used_percentage: 99 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(18)
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour: { used_percentage: 33 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(33)
} finally {
vi.useRealTimers()
}
})
it.each(['full', 'claude-only'])('isolates %s checks on switch', async (cycle) => {
vi.useFakeTimers()
try {
const staleClaudeFetch = deferred<ProviderRateLimits>()
const incomingFetch = deferred<ProviderRateLimits>()
vi.mocked(fetchActiveClaudeRateLimits)
.mockImplementationOnce(async () => okProvider('claude', 9))
.mockImplementationOnce(() => staleClaudeFetch.promise)
.mockImplementationOnce(() => incomingFetch.promise)
mockFreshBackgroundProviderFetches()
const authGate = deferred<void>()
let resolverCalls = 0
const service = new ObservedRateLimitService()
await service.refresh()
expect(service.claudeCheckCompletedAt).toBe(Date.now())
service.setClaudeAuthPreparationResolver(async () => {
resolverCalls += 1
const outgoing = resolverCalls === 1
if (outgoing) {
await authGate.promise
}
return {
configDir: outgoing ? '/outgoing/.claude' : '/incoming/.claude',
runtime: 'host',
wslDistro: null,
wslLinuxConfigDir: null,
envPatch: {
CLAUDE_CONFIG_DIR: outgoing ? '/outgoing/.claude' : '/incoming/.claude'
},
provenance: outgoing ? 'managed:outgoing' : 'managed:incoming'
}
})
// Switch while the outgoing account resolver is suspended.
const firstRefresh = cycle === 'full' ? service.refresh() : service.refreshClaudeForTarget()
await flushMicrotasks()
const switchPromise =
cycle === 'full'
? service.refreshForClaudeAccountChange('outgoing-account')
: service.refreshClaudeForTarget({ runtime: 'wsl', wslDistro: 'Ubuntu' })
await flushMicrotasks()
authGate.resolve()
await flushMicrotasks(8)
// The stale resumed cycle must not authorize outgoing live posts on the new account.
const beforeOutgoingPost = service.getState().claude?.session?.usedPercent
service.ingestLiveClaudeRateLimits({
configDir: '/outgoing/.claude',
fiveHour: { used_percentage: 99 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(beforeOutgoingPost)
staleClaudeFetch.resolve(okProvider('claude', 18))
await vi.advanceTimersByTimeAsync(0)
expect(service.claudeCheckCompletedAt).toBeNull()
service.ingestLiveClaudeRateLimits({
configDir: '/incoming/.claude',
fiveHour: { used_percentage: 55 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(55)
expect(service.activeRefreshPlan).toEqual({ kind: 'full' })
incomingFetch.resolve(okProvider('claude', 18))
await Promise.all([firstRefresh, switchPromise])
expect(fetchActiveClaudeRateLimits).toHaveBeenCalledTimes(3)
expect(service.claudeCheckCompletedAt).toBe(Date.now())
} finally {
vi.useRealTimers()
}
})
it('keeps the newer weekly value when an idle session re-posts an older one for the same window', async () => {
vi.useFakeTimers()
try {
// OAuth and statusline reset timestamps differ in precision.
const sessionReset = Date.now() + 128 * 60 * 1000 + 123
const weeklyReset = Date.now() + 125 * 60 * 60 * 1000 + 456
const win = (usedPercent: number, resetsAt: number, windowMinutes: number) => ({
usedPercent,
windowMinutes,
resetsAt,
resetDescription: null
})
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValue({
...okProvider('claude', 10),
session: win(10, sessionReset, 300),
weekly: win(25, weeklyReset, 10080)
})
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
await service.refresh()
const fetched = service.getState().claude
const post = (session: number | null, weekly: number, weeklyResetAt = weeklyReset) =>
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour:
session === null
? null
: { used_percentage: session, resets_at: Math.floor(sessionReset / 1000) },
sevenDay: { used_percentage: weekly, resets_at: Math.floor(weeklyResetAt / 1000) }
})
// Idle sessions can drop the expired 5h window while repeating stale weekly data; discard the whole stale post.
await vi.advanceTimersByTimeAsync(60 * 1000)
post(null, 8)
expect(service.getState().claude).toEqual(fetched)
post(10, 8)
expect(service.getState().claude).toEqual(fetched)
post(null, 90, weeklyReset - 7 * 24 * 60 * 60 * 1000)
expect(service.getState().claude).toEqual(fetched)
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({
...errorProvider('claude', 'rate limited'),
usageMetadata: { retryAtMs: Date.now() + 60 * 60 * 1000, failureKind: 'rate-limited' }
})
await service.refresh()
const failed = service.getState().claude
post(10, 8)
expect(service.getState().claude).toEqual(failed)
post(10, 25)
expect(service.getState().claude?.session?.resetsAt).toBe(sessionReset)
expect(service.getState().claude?.status).toBe('ok')
expect(service.getState().claude?.usageMetadata?.retryAtMs).toBe(
failed?.usageMetadata?.retryAtMs
)
post(11, 25)
expect(service.getState().claude?.weekly?.resetsAt).toBe(weeklyReset)
const grownSessionReset = service.getState().claude?.session?.resetsAt
post(11, 26)
expect(service.getState().claude?.session?.resetsAt).toBe(grownSessionReset)
expect(service.getState().claude?.weekly?.usedPercent).toBe(26)
post(null, 1, weeklyReset + 7 * 24 * 60 * 60 * 1000)
expect(service.getState().claude?.weekly?.usedPercent).toBe(1)
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour: null,
sevenDay: { utilization: 0 }
})
expect(service.getState().claude?.weekly?.usedPercent).toBe(0)
} finally {
vi.useRealTimers()
}
})
})
@@ -0,0 +1,22 @@
import { describe, expect, it } from 'vitest'
import '../../../orca-runtime-tests/runtime-test-module-registration.spec'
import { createRuntime } from '../../../orca-runtime-tests/orca-runtime-test-fixtures.spec'
const CHAT = 'orca_session_id:0f9c2f6e-6c1b-4f5e-9d8a-2b7f3c4d5e6f'
describe('terminal commands addressed to a chat', () => {
it('refuses read and send as a chat session instead of a stale terminal handle', async () => {
const runtime = createRuntime()
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [] })
const refusal = {
code: 'terminal_unsupported_for_agent_session',
message: expect.stringContaining(`orca orchestration send --to ${CHAT}`)
}
await expect(runtime.readTerminal(CHAT)).rejects.toMatchObject(refusal)
await expect(
runtime.sendTerminal(CHAT, { text: 'hi', enter: true }, { inputKind: 'driving' })
).rejects.toMatchObject(refusal)
})
})
@@ -3,6 +3,7 @@
import type { OrchestrationDb } from '../../db/orchestration-db'
import { resolveStructuredWorkerAuthority } from './structured-worker-authority'
import { parseOrcaSessionAddress } from '../../../../../shared/orca-session-address'
const TERMINAL_HANDLE_STALE = 'terminal_handle_stale'
const AGENT_SESSION_HAS_NO_TERMINAL = 'terminal_unsupported_for_agent_session'
@@ -11,14 +12,23 @@ export function structuredWorkerTerminalRefusal(
handle: string,
db: OrchestrationDb | null | undefined
): Error {
if (!resolveStructuredWorkerAuthority(handle, db)) {
return new Error(TERMINAL_HANDLE_STALE)
if (resolveStructuredWorkerAuthority(handle, db)) {
return agentSessionRefusal(
`${handle} is an agent session, not a terminal, so terminal commands cannot address it. ` +
'Read its output with `orca terminal read` or `orca orchestration worker-read --source transcript`, ' +
'send it work with `orca orchestration send`, and open it from its chat tab.'
)
}
const error = new Error(
`${handle} is an agent session, not a terminal, so terminal commands cannot address it. ` +
'Read its output with `orca terminal read` or `orca orchestration worker-read --source transcript`, ' +
'send it work with `orca orchestration send`, and open it from its chat tab.'
)
Object.assign(error, { code: AGENT_SESSION_HAS_NO_TERMINAL })
return error
// A chat address never names a terminal, live or not.
if (parseOrcaSessionAddress(handle)) {
return agentSessionRefusal(
`${handle} is a chat session, not a terminal, so terminal commands cannot address it. ` +
`Message it with \`orca orchestration send --to ${handle}\`.`
)
}
return new Error(TERMINAL_HANDLE_STALE)
}
function agentSessionRefusal(message: string): Error {
return Object.assign(new Error(message), { code: AGENT_SESSION_HAS_NO_TERMINAL })
}
@@ -0,0 +1,24 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { createOrchestrationWorkerReleaseHarness } from './worker-release.test-support'
describe('worker-start --terminal with --agent', () => {
const h = createOrchestrationWorkerReleaseHarness()
beforeEach(() => h.setup())
afterEach(() => h.cleanup())
it('refuses, saying --terminal continues the running agent, before any Dispatch', async () => {
await expect(
h.call('orchestration.workerStart', {
from: 'term_coord',
terminal: 'term_worker',
agent: 'codex',
spec: 'reuse the worker'
})
).rejects.toMatchObject({
code: 'invalid_argument',
message:
'--terminal continues the agent already running there, in its current conversation. To start fresh, use --worktree or --agent without --terminal.'
})
expect(h.db.db.prepare('SELECT count(*) AS n FROM dispatch_contexts').get()).toEqual({ n: 0 })
})
})
@@ -12,6 +12,9 @@ import type { WorkerStartInput } from './worker-start-schema'
type WorkerStartLaunch = ReturnType<typeof resolveWorkerLaunchPreferences>
const TERMINAL_WITH_AGENT_REFUSAL =
'--terminal continues the agent already running there, in its current conversation. To start fresh, use --worktree or --agent without --terminal.'
export function validateFederatedWorkerStartPlacement(
params: WorkerStartInput,
createsWorktree: boolean
@@ -35,10 +38,7 @@ export function validateFederatedWorkerStartPlacement(
)
}
if (params.terminal && params.agent) {
throw new OrchestrationError(
'invalid_argument',
'--terminal reuses an existing agent and cannot combine with --agent.'
)
throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL)
}
if (!params.terminal && !params.agent) {
throw new OrchestrationError(
@@ -57,10 +57,7 @@ export function prepareLocalWorkerStart(args: {
const { params, createsWorktree, runtime } = args
assertWorkerLaunchPreferencesCreateTerminal(params)
if (params.terminal && params.agent) {
throw new OrchestrationError(
'invalid_argument',
'--terminal reuses an existing agent and cannot combine with --agent.'
)
throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL)
}
if (createsWorktree && params.terminal) {
throw new OrchestrationError(
@@ -116,10 +113,7 @@ export function prepareFederationAttachmentWorkerStart(args: {
)
}
if (params.terminal && params.agent) {
throw new OrchestrationError(
'invalid_argument',
'--terminal reuses an existing agent and cannot combine with --agent.'
)
throw new OrchestrationError('invalid_argument', TERMINAL_WITH_AGENT_REFUSAL)
}
return resolveWorkerStartAgent({
runtime,
@@ -6,16 +6,6 @@ function record(...fields: string[]): string {
}
describe('WSL Claude plugin metadata', () => {
it('decodes present files and retains missing files as null', () => {
const settings = JSON.stringify({ enabledPlugins: { 'plugin@market': true } })
const output = [
record('F', '0', '1', Buffer.from(settings).toString('base64')),
record('F', '1', '0', '')
].join('')
expect(parseWslClaudePluginMetadataOutput(output, 2)).toEqual([settings, null])
})
it('rejects malformed metadata responses', () => {
expect(() => parseWslClaudePluginMetadataOutput(record('F', '4', '1', ''), 1)).toThrow(
'invalid response'
@@ -1,4 +1,4 @@
import { chmod, lstat, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { chmod, mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { gunzipSync, gzipSync } from 'node:zlib'
@@ -136,33 +136,6 @@ describe('skill package creation and extraction', () => {
).rejects.toThrow('skill-package-tar-truncated')
})
it('cancels during streamed extraction and removes partial bytes', async () => {
const root = await temporaryDirectory()
const created = await createSkillPackageArchive({
sourceDirectory: await createSkill(root),
archivePath: join(root, 'package.tar.gz'),
packageId: 'package_1',
versionId: 'version_1'
})
let checks = 0
const signal = {
get aborted() {
checks += 1
return checks >= 3
}
} as AbortSignal
const destinationDirectory = join(root, 'cancelled-extraction')
await expect(
extractSkillPackageArchive({
archivePath: created.archivePath,
destinationDirectory,
signal
})
).rejects.toThrow('skill-install-cancelled')
await expect(lstat(destinationDirectory)).rejects.toMatchObject({ code: 'ENOENT' })
})
it('rejects content checksum and SKILL identity mismatches', async () => {
const root = await temporaryDirectory()
const created = await createSkillPackageArchive({
@@ -69,23 +69,4 @@ describe('SkillSharePreparationService', () => {
expect(prepared.skills?.[0]?.executablePaths).toEqual(['run.sh'])
})
it('enforces the preparation cap while archives are still being created', async () => {
const { root, source } = await createSource()
const service = new SkillSharePreparationService(join(root, 'preparations'), {
findOwnedPackageId: nameIsFree,
publishVersion: vi.fn(),
createShare: vi.fn()
})
const results = await Promise.allSettled(
Array.from({ length: 9 }, () => service.prepare({ sourceDirectory: source }))
)
expect(results.filter((result) => result.status === 'fulfilled')).toHaveLength(8)
expect(results.filter((result) => result.status === 'rejected')).toHaveLength(1)
expect(results.find((result) => result.status === 'rejected')).toMatchObject({
reason: new Error('skill-share-preparation-limit')
})
})
})
@@ -1,17 +1,18 @@
import { getMainHttpClient } from '../network/http-client'
import { resampleToRate } from './stt-audio-resample'
import { replaceRetiredSpeechModelId } from './model-catalog'
import {
CLOUD_TRANSCRIPTION_SAMPLE_RATE,
MAX_CLOUD_TRANSCRIPTION_SECONDS,
cloudTranscriptionTimeoutMs
} from '../../shared/dictation-finish-deadlines'
export const OPENAI_TRANSCRIPTION_MODEL_BY_ID: Record<string, string> = {
'openai-gpt-transcribe': 'gpt-transcribe'
}
export const OPENAI_TRANSCRIPTION_URL = 'https://api.openai.com/v1/audio/transcriptions'
const CLOUD_TRANSCRIPTION_SAMPLE_RATE = 16000
const MAX_CLOUD_AUDIO_SAMPLES = 10 * 60 * CLOUD_TRANSCRIPTION_SAMPLE_RATE
// Room to answer plus the upload time of the WAV at 1 Mbit/s (125 bytes per ms).
const TRANSCRIPTION_RESPONSE_ALLOWANCE_MS = 30_000
const UPLOAD_BYTES_PER_MS = 125
const MAX_CLOUD_AUDIO_SAMPLES = MAX_CLOUD_TRANSCRIPTION_SECONDS * CLOUD_TRANSCRIPTION_SAMPLE_RATE
export type OpenAiTranscriptionResponse = {
text?: unknown
@@ -154,9 +155,7 @@ export class OpenAiTranscriptionSession {
// A named WAV blob satisfies multipart uploads without temporary files.
form.append('file', new Blob([wav], { type: 'audio/wav' }), 'dictation.wav')
const timeout = AbortSignal.timeout(
TRANSCRIPTION_RESPONSE_ALLOWANCE_MS + Math.ceil(wav.byteLength / UPLOAD_BYTES_PER_MS)
)
const timeout = AbortSignal.timeout(cloudTranscriptionTimeoutMs(this.audioSamples))
try {
return await this.upload(form, AbortSignal.any([this.abortController.signal, timeout]))
} catch (error) {
+2 -2
View File
@@ -7,8 +7,8 @@ import {
} from './stt-session-state'
import { waitForSttWorkerStop, type SttWorkerStopOutcome } from './stt-worker-stop'
import { STT_WORKER_HUNG_ERROR } from './stt-worker-process'
import { LOCAL_DICTATION_STOP_TIMEOUT_MS } from '../../shared/dictation-finish-deadlines'
const STOP_DICTATION_TIMEOUT_MS = 60_000
// A cancel waits only this long behind a busy decode before giving up on it.
const DISCARD_DICTATION_TIMEOUT_MS = 2_000
@@ -74,7 +74,7 @@ function stopLocalSession(
worker: engine.worker,
streamId: session.streamId,
sink: session.sink,
timeoutMs: discard ? DISCARD_DICTATION_TIMEOUT_MS : STOP_DICTATION_TIMEOUT_MS,
timeoutMs: discard ? DISCARD_DICTATION_TIMEOUT_MS : LOCAL_DICTATION_STOP_TIMEOUT_MS,
discard,
finish: (outcome) => finishLocalStop(state, session, engine, outcome, discard)
})
+1 -1
View File
@@ -101,7 +101,7 @@ export function createMainWindow(
const settings = store?.getSettings()
browserManager.setDictationShortcutForwardingPredicate(() => {
const voice = store?.getSettings().voice
// Guests forward only keydown, so Hold's release can't reach the renderer; the page keeps the key then.
// Chromium drops a page's key releases after a press cancelled here, so Hold can't see its release; the page keeps the key then.
return voice?.enabled === true && voice.dictationMode !== 'hold'
})
const windowMaterial = resolveWindowMaterial(
@@ -1,198 +0,0 @@
// @vitest-environment happy-dom
import {
deferred,
editState,
flushPromises,
jiraIssue,
otherIssue,
runtimeMocks,
saveTitle,
selectIssue,
store,
StoreBackedWorkspace
} from './__mocks__/jira-issue-workspace-edit-fixture'
import { act, fireEvent, render, screen } from '@testing-library/react'
import { describe, expect, it, vi } from 'vitest'
import type { JiraIssue, JiraMutationResult } from '../../../shared/jira/jira-types'
import type { RuntimeClientTarget } from '../../../shared/runtime-client-target'
import { getDefaultSettings } from '../../../shared/constants'
import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context'
import { TooltipProvider } from '@/components/ui/tooltip'
import JiraIssueWorkspace from './JiraIssueWorkspace'
describe('JiraIssueWorkspace optimistic edits', () => {
it.each([true, false])(
'captures the default host when a save settles after navigation (%s)',
async (ok) => {
const oldSave = deferred<JiraMutationResult>()
runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(oldSave.promise)
const contextKey = getProviderRuntimeContextKey(editState.settings)
const view = render(
<TooltipProvider>
<JiraIssueWorkspace issue={jiraIssue('Old title')} onUse={vi.fn()} onClose={vi.fn()} />
</TooltipProvider>
)
await flushPromises()
saveTitle('Old title', 'Local edit')
await flushPromises()
editState.settings = { ...getDefaultSettings(''), activeRuntimeEnvironmentId: 'remote-1' }
runtimeMocks.jiraGetIssueForTarget.mockImplementation(async (source: RuntimeClientTarget) =>
jiraIssue(source.kind === 'environment' ? 'Remote title' : 'Local edit')
)
view.rerender(
<TooltipProvider>
<JiraIssueWorkspace issue={jiraIssue('Remote title')} onUse={vi.fn()} onClose={vi.fn()} />
</TooltipProvider>
)
await flushPromises()
await act(async () =>
oldSave.resolve(ok ? { ok: true } : { ok: false, error: 'Local edit rejected' })
)
await flushPromises()
expect(runtimeMocks.jiraUpdateIssueForTarget).toHaveBeenCalledWith(
{ kind: 'local' },
'ENG-1',
{ title: 'Local edit' },
'site-1'
)
expect(runtimeMocks.jiraGetIssueForTarget).toHaveBeenLastCalledWith(
ok ? { kind: 'local' } : { kind: 'environment', environmentId: 'remote-1' },
'ENG-1',
'site-1'
)
expect(store.patchJiraIssue).toHaveBeenLastCalledWith(
'ENG-1',
expect.objectContaining({ title: ok ? 'Local edit' : 'Old title' }),
expect.objectContaining({ contextKey, siteId: 'site-1' })
)
expect(screen.getByDisplayValue('Remote title')).toBeDefined()
}
)
it('keeps loaded and submitted comments while a title save patches the shared cache', async () => {
runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise)
runtimeMocks.jiraIssueCommentsForTarget.mockResolvedValue([
{ id: 'server', body: 'Existing comment', createdAt: '2026-09-01' }
])
runtimeMocks.jiraAddIssueCommentForTarget.mockResolvedValue({ ok: true, id: 'added' })
render(<StoreBackedWorkspace initial={jiraIssue('Old title')} />)
await flushPromises()
fireEvent.change(screen.getByPlaceholderText('Add a Jira comment...'), {
target: { value: 'New comment' }
})
fireEvent.click(screen.getByRole('button', { name: 'Comment' }))
await flushPromises()
saveTitle('Old title', 'New title')
await flushPromises()
expect(screen.getByText('Existing comment')).toBeDefined()
expect(screen.getByText('New comment')).toBeDefined()
expect(runtimeMocks.jiraIssueCommentsForTarget).toHaveBeenCalledTimes(1)
})
it('keeps a cleared priority cleared when an older detail load arrives', async () => {
const initialLoad = deferred<JiraIssue>()
const initial = jiraIssue('Old title', { priority: { id: '1', name: 'High' } })
runtimeMocks.jiraGetIssueForTarget.mockReturnValue(initialLoad.promise)
runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise)
render(<StoreBackedWorkspace initial={initial} />)
await flushPromises()
fireEvent.click(screen.getByRole('button', { name: 'High' }))
fireEvent.click(await screen.findByRole('button', { name: 'No priority' }))
await act(async () => initialLoad.resolve(initial))
await flushPromises()
expect(screen.queryByRole('button', { name: 'High' })).toBeNull()
expect(runtimeMocks.jiraGetIssueForTarget).toHaveBeenCalledTimes(1)
expect(runtimeMocks.jiraIssueCommentsForTarget).toHaveBeenCalledTimes(1)
})
it('allows editing a newly opened issue while an earlier save is still pending', async () => {
const oldSave = deferred<{ ok: true }>()
runtimeMocks.jiraUpdateIssueForTarget
.mockReturnValueOnce(oldSave.promise)
.mockResolvedValue({ ok: true })
runtimeMocks.jiraGetIssueForTarget.mockImplementation(
async (_settings: unknown, key: string) =>
key === 'ENG-2' ? otherIssue : jiraIssue(editState.serverTitle)
)
render(<StoreBackedWorkspace initial={jiraIssue('Old title')} />)
await flushPromises()
saveTitle('Old title', 'New title')
await act(async () => selectIssue(otherIssue))
await flushPromises()
saveTitle('Other issue', 'Other updated')
await flushPromises()
expect(runtimeMocks.jiraUpdateIssueForTarget).toHaveBeenCalledTimes(2)
await act(async () => oldSave.resolve({ ok: true }))
await flushPromises()
expect(screen.getByText('ENG-2')).toBeDefined()
})
it('still hydrates fields the user did not edit when the initial load lands late', async () => {
const initialLoad = deferred<JiraIssue>()
runtimeMocks.jiraGetIssueForTarget.mockImplementationOnce(() => initialLoad.promise)
runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(deferred<{ ok: true }>().promise)
render(<StoreBackedWorkspace initial={jiraIssue('Old title')} />)
await flushPromises()
saveTitle('Old title', 'New title')
await flushPromises()
await act(async () => initialLoad.resolve(jiraIssue('Old title', { labels: ['backend'] })))
await flushPromises()
expect(screen.getByDisplayValue('New title')).toBeDefined()
expect(screen.getByDisplayValue('backend')).toBeDefined()
})
it.each([
['succeeds', { ok: true }],
['fails', { ok: false, error: 'Nope' }]
] as const)(
'stays on the newly opened issue when a save for the previous one %s',
async (_, outcome) => {
// The task page reuses this instance; a late save must not restore a previously selected issue.
const update = deferred<typeof outcome>()
runtimeMocks.jiraUpdateIssueForTarget.mockReturnValue(update.promise)
runtimeMocks.jiraGetIssueForTarget.mockImplementation(
async (_settings: unknown, key: string) =>
key === 'ENG-2' ? otherIssue : jiraIssue(editState.serverTitle)
)
render(<StoreBackedWorkspace initial={jiraIssue('Old title')} />)
await flushPromises()
saveTitle('Old title', 'New title')
await flushPromises()
await act(async () => selectIssue(otherIssue))
await flushPromises()
expect(screen.getByText('ENG-2')).toBeDefined()
editState.serverTitle = 'New title'
await act(async () => update.resolve(outcome))
await flushPromises()
expect(screen.getByText('ENG-2')).toBeDefined()
expect(screen.queryByText('ENG-1')).toBeNull()
expect(screen.getByDisplayValue('Other issue')).toBeDefined()
}
)
it('does not let a slow initial load overwrite a title saved meanwhile', async () => {
const initialLoad = deferred<JiraIssue>()
runtimeMocks.jiraGetIssueForTarget
.mockImplementationOnce(() => initialLoad.promise)
.mockImplementation(async () => jiraIssue(editState.serverTitle))
runtimeMocks.jiraUpdateIssueForTarget.mockImplementation(async () => {
editState.serverTitle = 'New title'
return { ok: true }
})
render(<StoreBackedWorkspace initial={jiraIssue('Old title')} />)
await flushPromises()
saveTitle('Old title', 'New title')
await flushPromises()
await act(async () => initialLoad.resolve(jiraIssue('Old title')))
await flushPromises()
expect(screen.getByDisplayValue('New title')).toBeDefined()
})
})
@@ -132,18 +132,6 @@ describe('AutomationsPage refresh', () => {
expect(reads()).toHaveLength(beforeEvents + 2)
}
)
it('does not re-run the whole refresh when the settings identity changes', async () => {
const { rerender } = await renderPage()
expect(api.automations.list).toHaveBeenCalledTimes(1)
mocks.state.settings = { ...(mocks.state.settings as Record<string, unknown>) }
await rerender()
// Settings no longer aim the list, so a new settings object is not a reason
// to re-fetch every host.
expect(api.automations.list).toHaveBeenCalledTimes(1)
})
})
describe('AutomationsPage selection', () => {
@@ -75,7 +75,8 @@ function useIsCloudModel(): boolean {
let current = true
if (!catalogRequest) {
catalogRequest = Promise.resolve()
.then(() => window.api.speech.getCatalog())
// The paired web client's fallback resolves with nothing rather than a list.
.then(async () => (await window.api.speech.getCatalog()) ?? [])
.catch(() => [])
}
void catalogRequest.then((catalog) => {
@@ -1,257 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { DictationState } from '../../../../shared/speech-types'
import type { GlobalSettings } from '../../../../shared/global-settings-types'
import { getDefaultSettings, getDefaultVoiceSettings } from '../../../../shared/constants'
import { useHoldDictationGesture } from './use-hold-dictation-gesture'
import { dictationShortcutModeSettings } from '../../../../shared/dictation-shortcut-mode'
const originalUserAgent = navigator.userAgent
let root: Root | null = null
let container: HTMLDivElement | null = null
let dictationState: DictationState
let dictationMode: 'auto' | 'hold'
let terminalShortcutPolicy: 'orca-first' | 'terminal-first'
let startDictation: ReturnType<typeof vi.fn<() => void>>
let stopDictation: ReturnType<typeof vi.fn<() => void>>
function setUserAgent(userAgent: string): void {
Object.defineProperty(navigator, 'userAgent', {
configurable: true,
value: userAgent
})
}
function holdSettings(): GlobalSettings {
return {
...getDefaultSettings('/home/test'),
terminalShortcutPolicy,
voice: {
...getDefaultVoiceSettings(),
enabled: true,
sttModel: 'test-model',
...dictationShortcutModeSettings(dictationMode)
}
}
}
function Probe(): null {
useHoldDictationGesture({
canStartDictation: () => dictationState === 'idle',
isDictationUnderway: () => dictationState === 'starting' || dictationState === 'listening',
keybindings: {},
settings: holdSettings(),
startDictation,
stopDictation
})
return null
}
function dispatchKeyDown(init: KeyboardEventInit): KeyboardEvent {
const event = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
window.dispatchEvent(event)
return event
}
function dispatchKeyUp(init: KeyboardEventInit): KeyboardEvent {
const event = new KeyboardEvent('keyup', { bubbles: true, cancelable: true, ...init })
window.dispatchEvent(event)
return event
}
async function renderProbe(): Promise<void> {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
await act(async () => {
root?.render(<Probe />)
})
}
function beginHold(init: KeyboardEventInit = {}): void {
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, ...init })
})
dictationState = 'listening'
}
beforeEach(() => {
setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0)')
dictationState = 'idle'
dictationMode = 'hold'
terminalShortcutPolicy = 'orca-first'
startDictation = vi.fn<() => void>()
stopDictation = vi.fn<() => void>()
})
afterEach(async () => {
if (root) {
await act(async () => {
root?.unmount()
})
}
root = null
container?.remove()
container = null
setUserAgent(originalUserAgent)
vi.clearAllMocks()
})
describe('useHoldDictationGesture', () => {
it('stops after a layout-aware shortcut key release drops the modifier flag', async () => {
await renderProbe()
beginHold({ key: 'e', code: 'KeyD' })
act(() => {
dispatchKeyUp({ key: 'e', code: 'KeyD', metaKey: false })
})
expect(startDictation).toHaveBeenCalledTimes(1)
expect(stopDictation).toHaveBeenCalledTimes(1)
})
it('stops when the required modifier is released before the shortcut key', async () => {
await renderProbe()
beginHold()
act(() => {
dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false })
})
expect(startDictation).toHaveBeenCalledTimes(1)
expect(stopDictation).toHaveBeenCalledTimes(1)
})
it('keeps a held dictation when its callbacks and keybindings are re-created', async () => {
await renderProbe()
beginHold()
const firstStopDictation = stopDictation
startDictation = vi.fn<() => void>()
stopDictation = vi.fn<() => void>()
await act(async () => {
root?.render(<Probe />)
})
expect(firstStopDictation).not.toHaveBeenCalled()
expect(stopDictation).not.toHaveBeenCalled()
act(() => {
dispatchKeyUp({ key: 'e', code: 'KeyE', metaKey: false })
})
expect(stopDictation).toHaveBeenCalledTimes(1)
})
it('does not restart from key repeat after dictation stopped on its own', async () => {
await renderProbe()
beginHold()
dictationState = 'idle'
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true })
})
expect(startDictation).toHaveBeenCalledTimes(1)
})
})
describe('useHoldDictationGesture in Auto mode', () => {
let now = 0
beforeEach(() => {
dictationMode = 'auto'
now = 1000
vi.spyOn(performance, 'now').mockImplementation(() => now)
})
it('keeps recording after a tap and stops on the next press', async () => {
await renderProbe()
// macOS drops the E keyup under Cmd, so the tap ends only when Cmd lets go.
beginHold()
now += 600
act(() => {
dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false })
})
expect(stopDictation).not.toHaveBeenCalled()
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true })
})
expect(startDictation).toHaveBeenCalledTimes(1)
expect(stopDictation).toHaveBeenCalledTimes(1)
})
it('stops on release after a press held for 300 ms', async () => {
await renderProbe()
beginHold()
now += 300
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true })
})
act(() => {
dispatchKeyUp({ key: 'Meta', code: 'MetaLeft', metaKey: false })
})
expect(startDictation).toHaveBeenCalledTimes(1)
expect(stopDictation).toHaveBeenCalledTimes(1)
})
it('starts a hold pressed while the last dictation was still finishing', async () => {
await renderProbe()
dictationState = 'stopping'
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true })
})
dictationState = 'idle'
act(() => {
dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, repeat: true })
})
expect(stopDictation).not.toHaveBeenCalled()
expect(startDictation).toHaveBeenCalledTimes(1)
})
it('leaves the shortcut to the IME while composing', async () => {
await renderProbe()
const event = dispatchKeyDown({ key: 'e', code: 'KeyE', metaKey: true, isComposing: true })
expect(event.defaultPrevented).toBe(false)
expect(startDictation).not.toHaveBeenCalled()
})
it('leaves the shortcut to a terminal that owns its keys', async () => {
terminalShortcutPolicy = 'terminal-first'
await renderProbe()
const terminalInput = document.createElement('textarea')
terminalInput.className = 'xterm-helper-textarea'
document.body.appendChild(terminalInput)
const event = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
key: 'e',
code: 'KeyE',
metaKey: true
})
act(() => {
terminalInput.dispatchEvent(event)
})
terminalInput.remove()
expect(event.defaultPrevented).toBe(false)
expect(startDictation).not.toHaveBeenCalled()
})
})
@@ -102,28 +102,6 @@ it('keeps the branch checkout strip open after selecting a badge context-menu ac
expect(container.querySelector('form')?.textContent).toContain('Check out branch topic?')
})
it('renders converging branch lanes and a detached root without duplicate child keys', async () => {
const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
getHistory.mockReset().mockResolvedValue({
...result,
items: [
{ id: 'a', subject: 'a', message: 'a', parentIds: ['root'] },
{ id: 'b', subject: 'b', message: 'b', parentIds: ['root'] },
{ id: 'c', subject: 'c', message: 'c', parentIds: ['root'] },
{ id: 'detached', subject: 'detached', message: 'detached', parentIds: [] },
{ id: 'root', subject: 'root', message: 'root', parentIds: [] }
]
})
await act(async () =>
root.render(
<TooltipProvider>
<GitGraphTab worktreeId={workspaceId} />
</TooltipProvider>
)
)
expect(errors.mock.calls.filter(([message]) => String(message).includes('same key'))).toEqual([])
})
it('recovers silently after each later token expiry and ignores refreshes for other worktrees', async () => {
let history: ReturnType<typeof useGitGraphHistory>
function History() {
@@ -1,39 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MarkdownPreviewDocumentClient } from './markdown-preview-document-client'
import {
MARKDOWN_PREVIEW_WORKER_TIMEOUT_MS,
type MarkdownPreviewWorkerResult
} from './markdown-preview-document-types'
class WorkerTransport extends EventTarget implements Worker {
onmessage: Worker['onmessage'] = null
onerror: Worker['onerror'] = null
onmessageerror: Worker['onmessageerror'] = null
postMessage = vi.fn<(message: unknown) => void>()
terminate = vi.fn()
reply(result: MarkdownPreviewWorkerResult): void {
this.onmessage?.(new MessageEvent('message', { data: result }))
}
}
afterEach(() => vi.useRealTimers())
describe('Markdown preview worker ownership', () => {
it('cancels a timed-out search without terminating a working preview', async () => {
vi.useFakeTimers()
const worker = new WorkerTransport()
const failure = vi.fn()
const client = new MarkdownPreviewDocumentClient(worker, failure)
const search = client.request({ type: 'search', query: 'needle' }).catch((error) => error)
await vi.advanceTimersByTimeAsync(MARKDOWN_PREVIEW_WORKER_TIMEOUT_MS)
expect(await search).toEqual(new Error('Preview search timed out.'))
expect(worker.postMessage).toHaveBeenLastCalledWith({ id: 2, type: 'cancel-search' })
expect(worker.terminate).not.toHaveBeenCalled()
expect(failure).not.toHaveBeenCalled()
worker.reply({ id: 1, type: 'search', matches: [], truncated: false })
const blocks = client.request({ type: 'blocks', indices: [0] })
worker.reply({ id: 3, type: 'blocks', blocks: [] })
expect(await blocks).toMatchObject({ type: 'blocks' })
expect(vi.getTimerCount()).toBe(0)
client.close()
})
})
@@ -1,47 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
import { createGlobalSettingsFixture } from '../../../../shared/global-settings-test-fixture'
import { getDefaultVoiceSettings } from '../../../../shared/constants'
import { useAppStore } from '../../store'
import { getPendingFeatureTips } from './feature-tip-startup-gate'
afterEach(() => {
useAppStore.setState(useAppStore.getInitialState(), true)
vi.unstubAllGlobals()
})
it('offers the rollout after historical completion and consumes only its own exposure', () => {
vi.stubGlobal('window', { api: { ui: { set: vi.fn().mockResolvedValue(undefined) } } })
const settings = createGlobalSettingsFixture({
voice: { ...getDefaultVoiceSettings(), enabled: true },
aiVaultSearch: { enabled: true, historyDays: null },
telemetry: {
optedIn: true,
installId: 'install',
existedBeforeTelemetryRelease: true,
chatUiLaunchTipCohort: 'control',
chatUiLaunchTipRolloutCohort: 'treatment'
}
})
useAppStore.setState({
settings,
featureTipsSeenIds: ['chat-ui-here', 'cmd-j-palette']
})
const pendingTipIds = () =>
getPendingFeatureTips({
seenTipIds: useAppStore.getState().featureTipsSeenIds,
cliInstalled: true,
featureInteractions: {},
chatUiLaunchTipVariant: 'chat-ui-off',
settings,
webClient: false
}).map((tip) => tip.id)
expect(pendingTipIds()).toEqual(['chat-ui-here'])
useAppStore.getState().markFeatureTipsSeen(['chat-ui-here'])
expect(useAppStore.getState().featureTipsSeenIds).toEqual([
'chat-ui-here',
'cmd-j-palette',
'chat-ui-here-rollout-v1'
])
expect(pendingTipIds()).toEqual([])
})
@@ -1,36 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import {
getWorkItemDetailsCacheKey,
invalidateWorkItemDetailsCacheByMatch,
touchWorkItemDetailsCache,
workItemDetailsCache
} from './work-item-details-cache'
vi.mock('@/lib/work-items/github/github-work-item-details-cache-events', () => ({
onGitHubWorkItemDetailsCacheMutation: vi.fn()
}))
const keyArgs = {
repoId: 'repo-1',
repoPath: '/home/fixture/widgets',
type: 'issue' as const,
number: 12,
issueSourcePreference: 'origin'
}
const ORIGIN = { owner: 'fork-owner', repo: 'widgets', host: 'github.com' }
const UPSTREAM = { owner: 'upstream-owner', repo: 'widgets', host: 'github.com' }
describe('issue detail cache repository identity', () => {
it('invalidates both repository variants after a mutation', () => {
const originKey = getWorkItemDetailsCacheKey({ ...keyArgs, ownerRepo: ORIGIN })
const upstreamKey = getWorkItemDetailsCacheKey({ ...keyArgs, ownerRepo: UPSTREAM })
touchWorkItemDetailsCache(originKey, { details: null, fetchedAt: 0 })
touchWorkItemDetailsCache(upstreamKey, { details: null, fetchedAt: 0 })
invalidateWorkItemDetailsCacheByMatch(keyArgs)
expect(workItemDetailsCache.has(originKey)).toBe(false)
expect(workItemDetailsCache.has(upstreamKey)).toBe(false)
})
})
@@ -1,145 +0,0 @@
// @vitest-environment happy-dom
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { i18n, loadRendererUiLanguage } from '@/i18n/i18n'
import { getProviderRuntimeContextKey } from '@/runtime/hosts/observations/provider-runtime-context'
import { TooltipProvider } from '../../ui/tooltip'
import { LinearIntegrationCard } from './linear-integration-card'
type StoreState = {
linearStatus: {
connected: boolean
workspaces?: { id: string; organizationName: string; displayName: string; email?: string }[]
}
linearStatusChecked: boolean
linearStatusContextKey: string | null
disconnectLinear: () => Promise<void>
disconnectLinearWorkspace: (workspaceId?: string) => Promise<void>
checkLinearConnection: (force?: boolean) => Promise<void>
testLinearConnection: (workspaceId: string) => Promise<{ ok: boolean; error?: string }>
settings: { activeRuntimeEnvironmentId: string | null }
openSettingsPage: () => void
openSettingsTarget: (target: { pane: string; repoId: string | null }) => void
}
const mocks = vi.hoisted(() => ({
store: { current: null as StoreState | null }
}))
vi.mock('@/store/index', () => ({
useAppStore: Object.assign(
(selector: (state: StoreState) => unknown) => {
if (!mocks.store.current) {
throw new Error('Store state was not installed')
}
return selector(mocks.store.current)
},
{ getState: () => mocks.store.current }
)
}))
vi.mock('@/components/linear-api-key-dialog', () => ({
LinearApiKeyDialog: ({ onConnected }: { onConnected?: () => void }) => (
<button type="button" data-testid="simulate-linear-connected" onClick={onConnected}>
Simulate Linear connected
</button>
)
}))
let root: Root | null = null
let container: HTMLDivElement | null = null
function installStore(
connected: boolean,
settings: StoreState['settings'] = { activeRuntimeEnvironmentId: null }
): StoreState {
const state: StoreState = {
linearStatus: {
connected,
workspaces: connected
? [
{
id: 'workspace-1',
organizationName: 'Acme',
displayName: 'Acme workspace',
email: 'linear@example.test'
}
]
: []
},
linearStatusChecked: true,
linearStatusContextKey: getProviderRuntimeContextKey(settings),
disconnectLinear: vi.fn(async () => {}),
disconnectLinearWorkspace: vi.fn(async () => {}),
checkLinearConnection: vi.fn(async () => {}),
testLinearConnection: vi.fn(async () => ({ ok: true })),
settings,
openSettingsPage: vi.fn(),
openSettingsTarget: vi.fn()
}
mocks.store.current = state
return state
}
async function renderCard(): Promise<HTMLDivElement> {
container = document.createElement('div')
document.body.appendChild(container)
root = createRoot(container)
await act(async () => {
root?.render(
<TooltipProvider>
<LinearIntegrationCard />
</TooltipProvider>
)
})
return container
}
describe('LinearIntegrationCard account scope', () => {
beforeEach(() => {
// Stub the skill scan so the CTA renders setup state rather than a bridge error.
Object.defineProperty(window, 'api', {
configurable: true,
value: {
skills: { discover: async () => ({ skills: [], sources: [], scannedAt: 0 }) }
}
})
})
afterEach(async () => {
if (root) {
await act(async () => {
root?.unmount()
})
}
root = null
container?.remove()
container = null
mocks.store.current = null
await i18n.changeLanguage(await loadRendererUiLanguage('en'))
Reflect.deleteProperty(window, 'api')
})
it('clears verification state after adding another Linear workspace', async () => {
installStore(true)
const rendered = await renderCard()
await act(async () => {
Array.from(rendered.querySelectorAll('button'))
.find((button) => button.textContent === 'Test')
?.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(rendered.textContent).toContain('Verified')
await act(async () => {
rendered
.querySelector<HTMLButtonElement>('[data-testid="simulate-linear-connected"]')
?.dispatchEvent(new MouseEvent('click', { bubbles: true }))
})
expect(rendered.textContent).not.toContain('Verified')
})
})
@@ -18,9 +18,6 @@ import {
useNativeChatDisclosures
} from '../../messages/disclosure/native-chat-disclosure-store'
import { i18n } from '@/i18n/i18n'
import { TranslationScopeProvider } from '@/i18n/translation-scope-provider'
{
const QUESTION = 'What would you like me to do next in this repo?'
const ASK_INPUT = { questions: [{ question: QUESTION }] }
@@ -288,66 +285,3 @@ import { TranslationScopeProvider } from '@/i18n/translation-scope-provider'
})
})
}
{
function runHeader(container: HTMLElement): HTMLElement {
const header = container.querySelector('button')
if (!header) {
throw new Error('run header did not render')
}
return header
}
describe('tool run sentences', () => {
afterEach(async () => {
cleanup()
await i18n.changeLanguage('en')
})
it('relabels an already-mounted run and its rows when the UI language changes', async () => {
const blocks: NativeChatBlock[] = [
{ type: 'tool-call', name: 'Bash', input: { command: 'false' }, state: 'failed' },
{ type: 'tool-result', output: 'exit 1', isError: true },
{
type: 'tool-call',
name: 'Agent',
input: { description: 'explore settings' },
state: 'completed'
}
]
const { container } = render(
<NativeChatToolRun
blocks={blocks}
backgroundTasks={[
{
type: 'background-task',
taskId: 'workflow-1',
kind: 'workflow',
label: 'task',
state: 'blocked',
outputFile: '/tmp/result.txt'
}
]}
expandSignal
/>,
{ wrapper: TranslationScopeProvider }
)
const header = runHeader(container)
expect(header).toHaveTextContent('Ran 1 command and ran 1 agent · 1 failed')
expect(screen.getByText('Subagent')).toBeInTheDocument()
expect(screen.getByText('Background workflow')).toBeInTheDocument()
expect(screen.getByText('Output: /tmp/result.txt')).toBeInTheDocument()
await act(async () => {
await i18n.changeLanguage('es')
})
expect(header).toHaveTextContent('Se ejecutó 1 comando y se ejecutó 1 agente · 1 fallidas')
expect(header).toHaveAccessibleName(/Llamadas a herramientas fallidas: 1/)
expect(screen.getByText('Subagente')).toBeInTheDocument()
expect(screen.getByText('Flujo de trabajo en segundo plano')).toBeInTheDocument()
expect(screen.getByText('Salida: /tmp/result.txt')).toBeInTheDocument()
expect(screen.getByText('bloqueado · con error')).toBeInTheDocument()
})
})
}
@@ -1,217 +0,0 @@
// @vitest-environment happy-dom
import type * as OriginalModule0 from '@/runtime/provider-accounts/observations/runtime-provider-accounts-client'
import '@testing-library/jest-dom/vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { NativeChatUsageLimitActionsProvider } from './NativeChatUsageLimitActions'
import { NativeChatNoticeRow } from '../messages/notices/NativeChatNoticeRow'
import type { NativeChatOrcaStopView } from '../messages/notices/native-chat-orca-stop-context'
import { TooltipProvider } from '@/components/ui/tooltip'
import type { NativeChatMessage } from '../../../../../shared/native-chat/native-chat-types'
import type { AgentType } from '../../../../../shared/agent-status/contracts/agent-status-types'
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
import type { AgentSessionStatusSummary } from '../../../../../shared/agent-session/agent-session-wire'
import type { useNativeChatUsageLimitAutoContinue } from './use-native-chat-usage-limit-auto-continue'
const mocks = vi.hoisted(() => ({
readSnapshot: {
canSwitchAccount: true,
transcriptPath: '/work/chat.jsonl'
},
follows: true,
watch: vi.fn(),
options: vi.fn(),
snapshot: vi.fn(),
select: vi.fn(),
dialog: vi.fn()
}))
let status = new Map<string, Pick<AgentSessionStatusSummary, 'usageLimitContinue'>>()
vi.mock('@/runtime/native-chat/host-capabilities/structured-agent-session-host-capability', () => ({
useStructuredAgentSessionHostCapabilityState: () => 'supported'
}))
vi.mock('@/runtime/native-chat/status/structured-agent-session-status-feed', () => ({
getStructuredAgentSessionStatusFeed: () => ({
activate: () => () => {},
subscribe: () => () => {},
getSnapshot: () => status
})
}))
vi.mock('../../../runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: mocks.options
}))
vi.mock('@/runtime/native-chat/naming/structured-conversation-name', () => ({
useStructuredChatTabConversationName: () => 'My chat'
}))
vi.mock('../../../runtime/provider-accounts/ownership/use-active-account-owner', () => ({
useActiveAccountOwner: () => ({
target: { kind: 'environment', environmentId: 'other' },
wslHostDistro: null
})
}))
vi.mock('@/lib/windows-terminal-capabilities', () => ({
getWindowsTerminalCapabilityOwnerKey: () => 'local',
useWindowsTerminalCapabilities: () => ({ wslDistros: [] })
}))
vi.mock(
'@/runtime/provider-accounts/observations/runtime-provider-accounts-client',
async (importOriginal) => ({
...(await importOriginal<typeof OriginalModule0>()),
fetchProviderAccountsSnapshot: mocks.snapshot,
watchProviderAccounts: mocks.watch,
selectClaudeProviderAccount: mocks.select,
emptyClaudeAccountsState: () => ({
accounts: [],
activeAccountId: null,
activeAccountIdsByRuntime: { host: null, wsl: {} }
})
})
)
vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({
handleRunningClaudeSessionsAfterSwitch: vi.fn()
}))
vi.mock('@/components/agent-session-continuation/AgentSessionContinuationDialog', () => ({
AgentSessionContinuationDialog: (props: {
onOpenChange: (open: boolean) => void
onStarted?: () => void
}) => {
mocks.dialog(props)
return (
<>
<button onClick={() => props.onOpenChange(false)}>Cancel hand-off</button>
<button
onClick={() => {
props.onOpenChange(false)
props.onStarted?.()
}}
>
Start hand-off
</button>
</>
)
}
}))
beforeEach(() => {
status = new Map()
mocks.options.mockResolvedValue(mocks.readSnapshot)
mocks.watch.mockImplementation((target, handlers) => {
let closed = false
void mocks.snapshot(target).then((value: unknown) => {
if (!closed) {
handlers.onSnapshot(value)
}
})
return {
close: () => {
closed = true
}
}
})
})
afterEach(() => {
cleanup()
vi.clearAllMocks()
vi.useRealTimers()
mocks.follows = true
})
function row(
target: RuntimeClientTarget = { kind: 'local' },
offered = true,
agent: AgentType = 'claude',
messages: readonly NativeChatMessage[] = [],
recovery: Parameters<typeof NativeChatUsageLimitActionsProvider>[0]['recovery'] = {
readCurrent: true,
canSwitchAccount: mocks.follows
},
automatic?: ReturnType<typeof useNativeChatUsageLimitAutoContinue>
) {
const view: NativeChatOrcaStopView = {
hostLabel: null,
remoteHost: target.kind !== 'local',
continueAvailable: false,
offeredTurnItemId: null,
continueNow: vi.fn(),
usageLimitTurnItemId: offered ? 'cut' : null,
usageLimitAutoContinue: automatic,
onUsageLimitHandOffStarted: automatic?.kind === 'scheduled' ? automatic.cancel : undefined,
continueUsageLimit: vi.fn()
}
return (
<TooltipProvider>
<NativeChatUsageLimitActionsProvider
recovery={recovery}
view={view}
pane={{
tabId: 'tab',
sessionId: 'chat',
agent,
target,
isVisible: true,
isFocusedGroup: true
}}
directory={{
worktreeId: 'folder',
worktreePath: '/work',
runtimeEnvironmentId: target.kind === 'environment' ? target.environmentId : null
}}
messages={messages}
>
<NativeChatNoticeRow
agentName="Claude"
block={{
type: 'text',
text: 'Limited',
tone: 'warning',
failure: { kind: 'usageLimitReached' },
usageLimitTurnItemId: 'cut'
}}
/>
</NativeChatUsageLimitActionsProvider>
</TooltipProvider>
)
}
function expectInlineActions(accountName: string | null) {
const leadIn = screen.getByText('Continue this chat without waiting:')
const actions = leadIn.parentElement
const handOff = screen.getByRole('button', { name: 'Hand Off to Another Agent' })
const account = accountName ? screen.getByRole('button', { name: accountName }) : null
expect(actions).toHaveClass('flex', 'flex-wrap', 'items-center')
expect(Array.from(actions?.children ?? [])).toEqual([
leadIn,
...(account ? [account.parentElement] : []),
handOff
])
if (account) {
expect(account.parentElement).toHaveClass('w-32', 'shrink-0')
}
}
it('admits one preparation and discards it after Continue supersedes the cut', async () => {
let answer: (value: typeof mocks.readSnapshot) => void = () => {}
mocks.options.mockImplementation(
() =>
new Promise((resolve) => {
answer = resolve
})
)
mocks.follows = false
const view = render(row())
expect(
screen.getByText('Continue this chat without waiting:').parentElement?.querySelector('.w-32')
).toBeNull()
expectInlineActions(null)
const button = screen.getByRole('button', { name: 'Hand Off to Another Agent' })
fireEvent.click(button)
fireEvent.click(button)
expect(mocks.options).toHaveBeenCalledTimes(1)
expect(button).toBeDisabled()
view.rerender(row({ kind: 'local' }, false))
answer(mocks.readSnapshot)
await waitFor(() => expect(mocks.dialog).not.toHaveBeenCalled())
view.rerender(row())
mocks.options.mockResolvedValue(mocks.readSnapshot)
fireEvent.click(screen.getByRole('button', { name: 'Hand Off to Another Agent' }))
await screen.findByText('Cancel hand-off')
fireEvent.click(screen.getByText('Cancel hand-off'))
expect(screen.queryByText('Cancel hand-off')).toBeNull()
})
@@ -1,50 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { createPluginFrameEnvelopeHandler, type PluginFrameHostOptions } from './plugin-frame-host'
import { pluginWebviewFrameWindow } from './plugin-frame-host-lanes'
vi.mock('./plugin-panel-design-token-css', () => ({
currentPluginFrameTheme: () => ({ colorScheme: 'dark', tokens: '' })
}))
const guestContext = { userActivation: true, transport: 'guest' as const }
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
function declarativeGuest(overrides: Partial<PluginFrameHostOptions> = {}) {
const webview = { send: vi.fn() }
const onRender = vi.fn()
const onRefused = vi.fn()
const callHostMethod = vi.fn().mockResolvedValue({ ok: true, value: null })
const handle = createPluginFrameEnvelopeHandler({
surface: 'panel',
getFrameWindow: () => pluginWebviewFrameWindow(webview),
getSessionToken: () => 'token',
callHostMethod,
declarative: { onRender, onError: vi.fn(), onRefused },
...overrides
})
const render = (tree: unknown, revision = 1) =>
handle({ orca: 1, kind: 'evt', event: 'ui.render', payload: { revision, tree } }, guestContext)
return { handle, render, onRender, onRefused, callHostMethod, webview }
}
describe('declarative render lane', () => {
it("ignores the hidden guest's own activation for user-gesture methods", async () => {
const consumeHostActivation = vi.fn(() => false)
const { handle, callHostMethod } = declarativeGuest({ consumeHostActivation })
const open = (id: number) => ({
orca: 1,
kind: 'req',
id,
method: 'shell.openExternal',
params: { url: 'https://example.com' }
})
handle(open(1), guestContext)
await flush()
expect(callHostMethod).not.toHaveBeenCalled()
consumeHostActivation.mockReturnValue(true)
handle(open(2), { userActivation: false, transport: 'guest' })
await flush()
expect(callHostMethod).toHaveBeenCalledOnce()
})
})
@@ -1,49 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
markInputQuietSchedulerInput,
resetInputQuietSchedulerForTest
} from '@/lib/input-quiet-scheduler'
import type { AiVaultListResult } from '../../../../../../shared/ai-vault/contracts/ai-vault-types'
import { AiVaultSessionPublicationGate } from './ai-vault-session-publication-gate'
const FIRST: AiVaultListResult = { sessions: [], issues: [], scannedAt: '2026-08-09T00:00:00.000Z' }
const SECOND: AiVaultListResult = { ...FIRST, scannedAt: '2026-08-09T00:00:01.000Z' }
afterEach(() => {
vi.useRealTimers()
resetInputQuietSchedulerForTest()
})
describe('AiVaultSessionPublicationGate', () => {
// A chat-link snapshot right after a restart cancels the gate; it must not drop the saved list.
it('shows a late saved list after a cancel but never over a newer published list', async () => {
const shown = vi.fn()
const gate = new AiVaultSessionPublicationGate()
gate.showUntilPublished(Promise.resolve(FIRST), shown)
gate.cancel()
await Promise.resolve()
expect(shown).toHaveBeenCalledWith(FIRST)
const late = vi.fn()
gate.showUntilPublished(Promise.resolve(FIRST), late)
gate.publish(SECOND, vi.fn())
await Promise.resolve()
expect(late).not.toHaveBeenCalled()
})
it('still shows a late saved list when the list published meanwhile was cancelled before it landed', async () => {
vi.useFakeTimers()
const shown = vi.fn()
const published = vi.fn()
const gate = new AiVaultSessionPublicationGate()
gate.showUntilPublished(Promise.resolve(FIRST), shown)
markInputQuietSchedulerInput()
gate.publish(SECOND, published)
gate.cancel()
await Promise.resolve()
vi.advanceTimersByTime(1_000)
expect(published).not.toHaveBeenCalled()
expect(shown).toHaveBeenCalledWith(FIRST)
})
})
@@ -1,56 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { PRComment } from '../../../../../../shared/github/comment-types'
import {
canPostPRReviewThreadReply,
resolvePRReviewReplyThreadId
} from './pr-comments-ai-launch-ack'
function comment(overrides: Partial<PRComment> = {}): PRComment {
return {
id: 1,
author: 'alice',
authorAvatarUrl: '',
body: 'Please update this.',
createdAt: '2026-05-14T00:00:00Z',
url: 'https://github.com/acme/widgets/pull/42#discussion_r1',
...overrides
}
}
describe('canPostPRReviewThreadReply', () => {
// Review-summary anchors override thread metadata; their IDs would 404 on the nested replies endpoint.
it('rejects review summaries even when thread metadata is present', () => {
expect(
canPostPRReviewThreadReply(
comment({
id: 5,
threadId: 'T1',
path: 'src/a.ts',
url: 'https://github.com/acme/widgets/pull/42#pullrequestreview-999'
})
)
).toBe(false)
})
})
describe('resolvePRReviewReplyThreadId', () => {
it('refuses a path-only match when the file holds several threads', () => {
const existing = [
comment({ id: 1, threadId: 'T_one', path: 'src/a.ts', line: 3 }),
comment({ id: 2, threadId: 'T_two', path: 'src/a.ts', line: 40 })
]
expect(
resolvePRReviewReplyThreadId({
parent: comment({ id: 50, path: 'src/a.ts', line: undefined }),
existingComments: existing
})
).toBeUndefined()
// A line-scoped parent still matches its own thread.
expect(
resolvePRReviewReplyThreadId({
parent: comment({ id: 50, path: 'src/a.ts', line: 40 }),
existingComments: existing
})
).toBe('T_two')
})
})
@@ -1,36 +0,0 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { PR_CHECK_LOG_TAIL_EARLIER_SEPARATOR as separator } from '../../../../../../shared/source-control/checks/logs/check-job-log-tail-slice'
import { findInitialCheckLogDiagnostic } from './check-log-initial-diagnostic-position'
describe('synthetic diagnostic excerpts', () => {
it('keeps an inline diagnostic with stack context ahead of a later standalone error', () => {
const text = '[worker] failed TypeError: invalid argument\n at worker.ts:3:4\nError: later'
const anchor = findInitialCheckLogDiagnostic(text)
expect(anchor && text.slice(anchor.start, anchor.end)).toBe('TypeError: invalid argument')
expect(anchor && text.slice(anchor.nearbyStackStart, anchor.nearbyStackEnd)).toBe(
' at worker.ts:3:4'
)
})
it('does not borrow a diagnostic or its frame from across the omission boundary', () => {
const text = `[worker] caught Error: expected\n${separator}\nError: failed to open database at database.ts:4:5\n at real.ts:8:9`
const anchor = findInitialCheckLogDiagnostic(text)
expect(anchor && text.slice(anchor.start, anchor.end)).toBe(
'Error: failed to open database at database.ts:4:5'
)
expect(anchor && text.slice(anchor.nearbyStackStart, anchor.nearbyStackEnd)).toBe(
' at real.ts:8:9'
)
const fallback = findInitialCheckLogDiagnostic(
`[worker] caught Error: expected\n${separator}\n at real.ts:8:9`
)
expect(fallback?.nearbyStackStart).toBeUndefined()
})
it('retains unframed inline diagnostics as the recent-segment fallback', () => {
const text = `Error: earlier failure\n${separator}\n[worker] failed EACCES: open database\n##[error]Process completed with exit code 1`
const anchor = findInitialCheckLogDiagnostic(text)
expect(anchor && text.slice(anchor.start, anchor.end)).toBe('EACCES: open database')
})
})
@@ -1,40 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import { createEditorStore } from '@/store/slices/editor/editor-slice-test-harness'
import type { GitStatusEntry } from '../../../../../../shared/git/status/git-status-types'
import { openUncommittedEntry } from './open-uncommitted-entry'
vi.mock('sonner', () => ({ toast: { error: vi.fn() } }))
vi.mock('@/runtime/web-session-tabs-sync/closing/close-mirrored-editor-tab', () => ({
notifyHostOfMirroredEditorClose: vi.fn()
}))
function markdownEntry(overrides: Partial<GitStatusEntry> = {}): GitStatusEntry {
return {
path: 'docs/new.md',
status: 'untracked',
area: 'untracked',
...overrides
}
}
describe('openUncommittedEntry', () => {
it.each(['source', 'changes'] as const)('preserves an explicit %s choice on reselect', (mode) => {
const store = createEditorStore()
const entry = markdownEntry()
openUncommittedEntry(store.getState(), 'wt-1', '/repo', entry)
const fileId = store.getState().openFiles[0].id
if (mode === 'changes') {
store.getState().setEditorViewMode(fileId, 'changes')
} else {
store.getState().setMarkdownViewMode(fileId, 'source')
}
openUncommittedEntry(store.getState(), 'wt-1', '/repo', entry)
const state = store.getState()
expect(state.openFiles).toHaveLength(1)
expect(mode === 'changes' ? state.editorViewMode[fileId] : state.markdownViewMode[fileId]).toBe(
mode
)
})
})
@@ -1,215 +0,0 @@
// @vitest-environment happy-dom
import '@testing-library/jest-dom/vitest'
import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
import { toast } from 'sonner'
import { i18n } from '@/i18n/i18n'
import { getDefaultSettings } from '../../../../../shared/constants'
import type {
ClaudeManagedAccountSummary,
ClaudeRateLimitAccountsState
} from '../../../../../shared/managed-account-types'
import type { RuntimeClientTarget } from '../../../../../shared/runtime-client-target'
import { AccountsPane } from './AccountsPane'
import type { SettingsHostScope } from '../host-scope/settings-host-scope'
import type { SettingsNavigationTarget } from '@/lib/settings-navigation-types'
// Why: focus deliberately points at another server; the pane must follow hostScope only.
const focusedElsewhere = {
...getDefaultSettings('/synthetic'),
activeRuntimeEnvironmentId: 'focused-server'
}
const scopeFor = (environmentId: string | null): SettingsHostScope => ({
target: environmentId ? { kind: 'environment', environmentId } : { kind: 'local' },
available: true
})
const renderPane = (scope: SettingsHostScope): React.JSX.Element => (
<AccountsPane
settings={focusedElsewhere}
updateSettings={vi.fn()}
updateSettingsOrThrow={vi.fn()}
hostScope={scope}
/>
)
const fake = vi.hoisted(() => {
const state: {
query: string
pendingSelect: ((roster: unknown) => void) | null
write: ReturnType<typeof vi.fn>
add: ReturnType<typeof vi.fn>
navigate: (target: SettingsNavigationTarget) => void
rosters: Map<string, unknown>
watchedTargets: unknown[]
selects: unknown[][]
} = {
query: 'claude',
pendingSelect: null,
write: vi.fn(),
add: vi.fn(),
navigate: () => {},
rosters: new Map(),
watchedTargets: [],
selects: []
}
return state
})
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn(), info: vi.fn() } }))
vi.mock('@/store/index', () => ({
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector({
settingsSearchQuery: fake.query,
settings: focusedElsewhere,
openSettingsTarget: (target: SettingsNavigationTarget) => fake.navigate(target),
openSettingsPage: fake.write,
rateLimits: {
codex: null,
codexTarget: { runtime: 'host', wslDistro: null },
minimax: null,
cursor: { updatedAt: 0 },
grok: { updatedAt: 0 },
inactiveClaudeAccounts: [],
claudeTarget: { runtime: 'host', wslDistro: null }
},
runtimeEnvironments: [],
runtimeStatusByEnvironmentId: new Map(),
recordFeatureInteraction: fake.write,
fetchSettings: fake.write,
fetchInactiveClaudeAccountUsage: fake.write
})
}))
vi.mock('@/runtime/provider-accounts/sign-in/runtime-antigravity-accounts-client', () => ({
callAntigravityAccounts: vi.fn(),
callAntigravityChatSignIn: vi.fn(),
subscribeAntigravityChatSignIn: vi.fn()
}))
vi.mock('@/runtime/provider-accounts/observations/runtime-provider-accounts-client', () => {
const empty = () => ({
accounts: [],
activeAccountId: null,
activeAccountIdsByRuntime: { host: null, wsl: {} }
})
return {
emptyClaudeAccountsState: empty,
emptyCodexAccountsState: empty,
getProviderAccountsOwnerKey: (target: RuntimeClientTarget) =>
target.kind === 'environment' ? target.environmentId : 'local',
watchProviderAccounts: (
target: RuntimeClientTarget,
handlers: { onSnapshot: (snapshot: unknown) => void }
) => {
fake.watchedTargets.push(target)
handlers.onSnapshot({
claude: fake.rosters.get(target.kind === 'environment' ? target.environmentId : 'local'),
codex: empty(),
rateLimits: null
})
return { close: vi.fn() }
},
fetchProviderAccountsSnapshot: async (target: RuntimeClientTarget) => ({
claude: fake.rosters.get(target.kind === 'environment' ? target.environmentId : 'local')
}),
selectClaudeProviderAccount: (...args: unknown[]) => {
fake.selects.push(args)
return new Promise((resolve) => {
fake.pendingSelect = resolve
})
},
selectCodexProviderAccount: fake.write,
removeClaudeProviderAccount: fake.write,
removeCodexProviderAccount: fake.write
}
})
function claudeRoster(id: string, email: string, active: boolean): ClaudeRateLimitAccountsState {
const account: ClaudeManagedAccountSummary = {
id,
email,
authMethod: 'subscription-oauth',
createdAt: 1,
updatedAt: 1,
lastAuthenticatedAt: 1
}
const activeId = active ? id : null
return {
accounts: [account],
activeAccountId: activeId,
activeAccountIdsByRuntime: { host: activeId, wsl: {} }
}
}
vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({
handleRunningClaudeSessionsAfterSwitch: vi.fn(async () => 'no-running-sessions')
}))
vi.mock('../../../runtime/provider-accounts/ownership/use-active-account-owner', () => ({
useActiveAccountOwner: () => ({ target: { kind: 'local' }, wslHostDistro: null })
}))
vi.mock('@/lib/windows-terminal-capabilities', () => ({
getWindowsTerminalCapabilityOwnerKey: () => 'local',
useWindowsTerminalCapabilities: () => ({ wslDistros: ['Ubuntu'] })
}))
beforeEach(async () => {
await i18n.changeLanguage('en')
vi.mocked(toast.error).mockClear()
fake.query = 'claude'
fake.write.mockClear()
fake.add.mockReset()
fake.add.mockImplementation(async () => fake.rosters.get('local'))
fake.pendingSelect = null
fake.watchedTargets = []
fake.selects = []
fake.rosters.set('local', claudeRoster('acct-l', 'local@desktop.test', false))
fake.rosters.set('server-a', claudeRoster('acct-a', 'alpha@server-a.test', false))
fake.rosters.set('server-b', claudeRoster('acct-b', 'beta@server-b.test', false))
Object.assign(window, {
api: {
claudeAccounts: { add: fake.add },
minimaxCredentials: {
getStatus: vi.fn(async () => ({ cookieConfigured: false, apiKeyConfigured: false }))
},
codexConfigSync: {
status: vi.fn(async () => ({ state: 'synced', reason: null, systemConfigPath: '/x' }))
}
}
})
})
afterEach(() => {
cleanup()
vi.restoreAllMocks()
Reflect.deleteProperty(window, 'api')
})
it("drops a server's late account result after the page moves to another server", async () => {
const view = render(renderPane(scopeFor('server-a')))
await act(async () => {})
fireEvent.click(screen.getByText('alpha@server-a.test'))
expect(fake.pendingSelect).not.toBeNull()
await act(async () => view.rerender(renderPane(scopeFor('server-b'))))
expect(screen.getByText('beta@server-b.test')).toBeTruthy()
await act(async () => fake.pendingSelect?.(claudeRoster('acct-a', 'alpha@server-a.test', true)))
expect(screen.queryByText('alpha@server-a.test')).toBeNull()
expect(screen.getByText('beta@server-b.test')).toBeTruthy()
})
it('keeps a late account result once the pane is back on the server it was sent to', async () => {
const view = render(renderPane(scopeFor('server-a')))
await act(async () => {})
fireEvent.click(screen.getByText('alpha@server-a.test'))
for (const environmentId of ['server-b', 'server-a']) {
await act(async () => view.rerender(renderPane(scopeFor(environmentId))))
}
const alphaRow = (): HTMLElement => {
const row = screen.getByText('alpha@server-a.test').closest('button')
expect(row).not.toBeNull()
return row ?? document.body
}
expect(within(alphaRow()).queryByText('Active')).toBeNull()
await act(async () => fake.pendingSelect?.(claudeRoster('acct-a', 'alpha@server-a.test', true)))
expect(within(alphaRow()).getByText('Active')).toBeTruthy()
})
@@ -1,57 +0,0 @@
import { afterAll, describe, expect, it } from 'vitest'
import { i18n } from '@/i18n/i18n'
import { getDeveloperPermissionsPaneSearchEntries } from './developer-permissions-search'
import { matchesSettingsSearch } from '../search/settings-search'
// Use macOS 26’s actual Local Network translations (SecurityPrivacyExtension LOCAL_NETWORK).
const MACOS_LOCAL_NETWORK_LABEL = {
en: 'local network',
es: 'red local',
ja: 'ローカルネットワーク',
ko: '로컬 네트워크',
zh: '本地网络'
} as const
function getLanEntry() {
const entry = getDeveloperPermissionsPaneSearchEntries().find((candidate) =>
candidate.keywords?.includes('usb')
)
if (!entry) {
throw new Error('LAN, USB, and Bluetooth search entry is missing')
}
return entry
}
async function searchInLocale(locale: string, query: string): Promise<boolean> {
await i18n.changeLanguage(locale)
return matchesSettingsSearch(query, getLanEntry())
}
describe('developer permissions LAN search', () => {
afterAll(async () => {
await i18n.changeLanguage('en')
})
it.each(Object.entries(MACOS_LOCAL_NETWORK_LABEL))(
'finds the LAN row from the macOS Local Network wording in %s',
async (locale, label) => {
expect(await searchInLocale(locale, label)).toBe(true)
}
)
it('keeps the English LAN aliases findable in every locale', async () => {
for (const locale of Object.keys(MACOS_LOCAL_NETWORK_LABEL)) {
for (const query of ['lan', 'local network', 'local-network']) {
expect(await searchInLocale(locale, query)).toBe(true)
}
}
})
it('keeps the localized LAN wording findable', async () => {
expect(await searchInLocale('zh', '局域网')).toBe(true)
expect(await searchInLocale('ja', 'LAN')).toBe(true)
expect(await searchInLocale('ko', 'LAN')).toBe(true)
expect(await searchInLocale('es', 'LAN')).toBe(true)
})
})
@@ -1,49 +0,0 @@
import { afterEach, describe, expect, it } from 'vitest'
import {
agentTabActionId,
getKeybindingDefinition
} from '../../../../../shared/keybindings/definitions'
import type {
KeybindingActionId,
KeybindingDefinition
} from '../../../../../shared/keybindings/types'
import { i18n } from '@/i18n/i18n'
import { localizeKeybindingDefinition } from './keybinding-title-copy'
function definition(actionId: KeybindingActionId): KeybindingDefinition {
const found = getKeybindingDefinition(actionId)
if (!found) {
throw new Error(`missing ${actionId}`)
}
return found
}
describe('localizeKeybindingDefinition', () => {
afterEach(async () => {
await i18n.changeLanguage('en')
})
it('localizes built-in titles, keeps English searchable, and leaves plugin titles alone', async () => {
await i18n.changeLanguage('ko')
const quickOpen = definition('worktree.quickOpen')
const localized = localizeKeybindingDefinition(quickOpen)
expect(localized.title).not.toBe(quickOpen.title)
expect(localized.group).not.toBe(quickOpen.group)
expect(localized.searchKeywords).toEqual(
expect.arrayContaining([quickOpen.title, quickOpen.group])
)
const agentTab = definition(agentTabActionId('claude'))
const agentTitle = localizeKeybindingDefinition(agentTab).title
expect(agentTitle).not.toBe(agentTab.title)
expect(agentTitle).toContain('Claude')
const plugin: KeybindingDefinition = {
...quickOpen,
id: 'plugin:orca-samples.tasks/open',
title: 'Open Tasks — Tasks',
group: 'Plugins'
}
expect(localizeKeybindingDefinition(plugin)).toBe(plugin)
})
})
@@ -1,49 +0,0 @@
// @vitest-environment happy-dom
import { cleanup, render, screen } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createGlobalSettingsFixture } from '../../../../../shared/global-settings-test-fixture'
import { useAppStore } from '../../../store'
import { TerminalInteractionSection } from './TerminalInteractionSection'
const i18nMock = vi.hoisted(() => {
const translations: Record<string, string> = {}
return { language: 'en', translations }
})
vi.mock('@/i18n/i18n', () => ({
translate: (key: string, defaultValue: string) => i18nMock.translations[key] ?? defaultValue,
i18n: i18nMock
}))
vi.mock('@/i18n/localized-catalog', () => ({
createLocalizedCatalog: (factory: () => unknown) => factory
}))
describe('TerminalInteractionSection scroll on input', () => {
beforeEach(() => {
useAppStore.setState({ settingsSearchQuery: '' })
})
afterEach(() => {
cleanup()
i18nMock.language = 'en'
i18nMock.translations = {}
})
it('keeps the row visible for a localized search keyword', () => {
i18nMock.language = 'de'
i18nMock.translations = { 'components.settings.terminal.search.snap': 'einrasten' }
useAppStore.setState({ settingsSearchQuery: 'einrasten' })
render(
<TerminalInteractionSection
settings={createGlobalSettingsFixture()}
updateSettings={vi.fn()}
searchQuery="einrasten"
/>
)
expect(screen.getByRole('switch', { name: 'Scroll to Bottom on Input' })).toBeTruthy()
})
})
@@ -1,48 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { Repo } from '../../../../../../shared/repo-types'
import type { Worktree } from '../../../../../../shared/worktree/types'
import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity'
import { matchWorkspaceBoardWorktrees } from './workspace-kanban-search'
function worktree(overrides: Partial<Worktree> & { id: string }): Worktree {
return {
repoId: 'repo-a',
displayName: 'Workspace',
path: `/${overrides.id}`,
branch: 'main',
baseBranch: 'main',
isPinned: false,
sortOrder: 1,
hostId: 'local',
...overrides
} as Worktree
}
const repoMap = new Map<string, Repo>([
['repo-a', { id: 'repo-a', displayName: 'orca' } as Repo],
['repo-b', { id: 'repo-b', displayName: 'atlas' } as Repo]
])
function match(worktrees: Worktree[], query: string): ReadonlySet<string> | null {
return matchWorkspaceBoardWorktrees({ worktrees, query, repoMap })
}
function identities(...worktrees: Worktree[]): Set<string> {
return new Set(worktrees.map(getWorktreeHostIdentity))
}
describe('matchWorkspaceBoardWorktrees', () => {
it('separates two same-id host rows', () => {
const local = worktree({ id: 'shared', branch: 'refs/heads/local-only' })
const remote = worktree({
id: local.id,
hostId: 'ssh:box',
branch: 'refs/heads/remote-only'
})
expect(match([local, remote], 'local-only')).toEqual(identities(local))
expect(match([local, remote], 'remote-only')).toEqual(identities(remote))
expect(match([local], 'local-only')).toEqual(identities(local))
})
})
@@ -1,164 +0,0 @@
// @vitest-environment happy-dom
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { ReactNode } from 'react'
import { useAppStore } from '@/store'
import { getDefaultSettings } from '../../../../shared/constants'
import {
accountHost,
accountTransport
} from '@/runtime/provider-accounts/observations/provider-account-observation.test-fixture'
import { ClaudeSwitcherMenu } from './ClaudeSwitcherMenu'
const mocks = vi.hoisted(() => ({ rpc: vi.fn() }))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: mocks.rpc
}))
vi.mock('@/lib/provider-accounts/claude-account-switch-sessions', () => ({
handleRunningClaudeSessionsAfterSwitch: vi.fn()
}))
vi.mock('@/lib/windows-terminal-capabilities', () => ({
useWindowsTerminalCapabilities: () => ({ wslDistros: [], isLoading: false }),
getWindowsTerminalCapabilityOwnerKey: () => 'local'
}))
vi.mock('./ProviderDetailsMenu', () => ({
ProviderDetailsMenu: ({ children }: { children: ReactNode }) => <div>{children}</div>
}))
vi.mock('@/components/ui/dropdown-menu', () => ({
DropdownMenuLabel: ({ children }: { children: ReactNode }) => <div>{children}</div>,
DropdownMenuSeparator: () => null,
DropdownMenuItem: ({
children,
disabled,
onSelect
}: {
children: ReactNode
disabled?: boolean
onSelect: (event: { preventDefault: () => void }) => void
}) => (
<div
role="menuitem"
aria-disabled={!!disabled}
onClick={() => {
if (!disabled) {
onSelect({ preventDefault: () => {} })
}
}}
>
{children}
</div>
)
}))
const initial = useAppStore.getState()
afterEach(() => {
cleanup()
useAppStore.setState(initial, true)
vi.clearAllMocks()
})
function deferred<T>() {
let resolve!: (value: T) => void
let reject!: (error: Error) => void
const promise = new Promise<T>((done, fail) => {
resolve = done
reject = fail
})
return { promise, resolve, reject }
}
function replacementOwner(id: string | null) {
useAppStore.setState((state) => ({
settings: { ...state.settings!, activeRuntimeEnvironmentId: id }
}))
}
function row(id: string) {
return screen.getByText(`${id}@example.com`).closest('[role="menuitem"]')!
}
async function expand() {
if (screen.queryByText('b@example.com')) {
return
}
fireEvent.click(screen.getAllByText('a@example.com')[0])
await act(async () => {})
}
it.each([
['select', 'resolve'],
['select', 'reject'],
['sign-in', 'resolve'],
['sign-in', 'reject']
] as const)(
'retires pending %s with its owner after late %s and admits a replacement action',
async (operation, settlement) => {
const local = accountHost(),
a = accountHost(),
b = accountHost()
const transport = accountTransport({ a, b })
const pending = deferred<typeof a.snapshot.claude>()
const select = vi.fn(() => pending.promise)
const reauthenticate = vi.fn(() => pending.promise)
if (operation === 'sign-in') {
local.snapshot.claude.accounts[1].needsSignIn = true
}
Object.defineProperty(window, 'api', {
configurable: true,
value: {
...window.api,
claudeAccounts: {
...window.api.claudeAccounts,
list: async () => local.snapshot.claude,
select,
reauthenticate
},
codexAccounts: { ...window.api.codexAccounts, list: async () => local.snapshot.codex }
}
})
mocks.rpc.mockImplementation(async (target) =>
target.environmentId === 'a' ? pending.promise : b.snapshot.claude
)
useAppStore.setState({
settings: {
...getDefaultSettings('/test'),
claudeManagedAccounts: local.snapshot.claude.accounts.map((account) => ({
...account,
managedAuthPath: '/unused'
})),
activeClaudeManagedAccountId: 'a',
activeClaudeManagedAccountIdsByRuntime: { host: 'a', wsl: {} },
activeRuntimeEnvironmentId: operation === 'sign-in' ? null : 'a'
},
fetchSettings: vi.fn(async () => {}),
fetchInactiveClaudeAccountUsage: vi.fn(async () => {})
})
render(<ClaudeSwitcherMenu claude={null} compact iconOnly />)
await act(async () => {})
await expand()
fireEvent.click(row('b'))
await act(async () => {})
expect(operation === 'sign-in' ? reauthenticate : mocks.rpc).toHaveBeenCalledTimes(1)
expect(row('b').getAttribute('aria-disabled')).toBe('true')
await act(async () => replacementOwner('b'))
await expand()
// The old answer is deliberately different from the replacement owner's authoritative roster.
const late = {
...a.snapshot.claude,
activeAccountId: 'b',
activeAccountIdsByRuntime: { host: 'b', wsl: {} }
}
await act(async () => {
if (settlement === 'resolve') {
pending.resolve(late)
} else {
pending.reject(new Error('Fixture operation failed'))
}
})
expect(row('b').getAttribute('aria-disabled')).toBe('false')
fireEvent.click(row('b'))
await act(async () => {})
expect(mocks.rpc).toHaveBeenLastCalledWith(
{ kind: 'environment', environmentId: 'b' },
'accounts.selectClaude',
{ accountId: 'b' },
{ timeoutMs: 30000 }
)
expect(transport.streams.some((stream) => stream.host === 'b')).toBe(true)
}
)
@@ -1,175 +0,0 @@
// @vitest-environment happy-dom
import { beforeEach, expect, it, vi } from 'vitest'
import type { RuntimeTerminalWait } from '../../../../shared/runtime-types'
import type { ExecutionHostId } from '../../../../shared/execution-host'
const mocks = vi.hoisted(() => ({
call: vi.fn(),
close: vi.fn(),
state: {
tabsByWorktree: { workspace: [{ id: 'tab', createdAt: 1 }] },
terminalLayoutsByTabId: {
tab: {
root: {
type: 'split',
first: { type: 'leaf', leafId: 'a' },
second: { type: 'leaf', leafId: 'b' }
},
ptyIdsByLeafId: { a: 'pty-a', b: 'pty-b' }
}
},
ptyIdsByTabId: { tab: ['pty-a', 'pty-b'] },
terminalPtyIncarnationsByPaneKey: { 'tab:a': 'inc-a', 'tab:b': 'inc-b' }
}
}))
vi.mock('@/store', () => ({ useAppStore: { getState: () => mocks.state } }))
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({
callRuntimeRpc: mocks.call
}))
vi.mock('@/runtime/native-chat/session-ownership/structured-agent-session-owner', () => ({
structuredAgentSessionTargetForHost: (host: string) =>
host === 'local' ? { kind: 'local' } : { kind: 'environment', environmentId: 'paired' }
}))
vi.mock('../terminal/terminal-tab-actions', () => ({ closeTerminalTab: mocks.close }))
import { closeCliChatResumeTerminal } from './cli-chat-resume-close-terminal'
const source = {
tabId: 'tab',
workspaceId: 'workspace',
paneKey: 'tab:a',
agent: 'claude',
providerSessionId: 'conversation',
executionHostId: 'local'
} as const
const hooks = (closing = vi.fn()) => ({ prepared: vi.fn(), closing, refused: vi.fn() })
function deferred<T>() {
let resolve: (value: T) => void = () => {}
const promise = new Promise<T>((done) => {
resolve = done
})
return { resolve, promise }
}
beforeEach(() => {
vi.clearAllMocks()
mocks.state.terminalPtyIncarnationsByPaneKey['tab:a'] = 'inc-a'
mocks.call.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.resolvePane') {
const leaf = params.paneKey.endsWith(':b') ? 'b' : 'a'
return {
terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` }
}
}
return { wait: { satisfied: true, status: 'exited', exitCode: 0 } }
})
mocks.close.mockImplementation((_tab, options) => {
options.beforeClose()
})
})
it.each<ExecutionHostId>(['local', 'runtime:paired'])(
'pins every split PTY before ordinary tab close on %s and waits for all exits',
async (executionHostId) => {
const exit = deferred<{
wait: Pick<RuntimeTerminalWait, 'satisfied' | 'status' | 'exitCode'>
}>()
mocks.call.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.resolvePane') {
const leaf = params.paneKey.endsWith(':b') ? 'b' : 'a'
return {
terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` }
}
}
return params.terminal === 'handle-b'
? exit.promise
: { wait: { satisfied: true, status: 'exited', exitCode: 0 } }
})
const closing = vi.fn(() =>
expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(2)
)
let finished = false
const closeHooks = hooks(closing)
const run = closeCliChatResumeTerminal(
{ ...source, executionHostId },
() => true,
closeHooks,
new AbortController().signal
).then((value) => {
finished = true
return value
})
await vi.waitFor(() => expect(closing).toHaveBeenCalledOnce())
expect(finished).toBe(false)
expect(closeHooks.prepared).toHaveBeenCalledOnce()
// Only the split's other pane can ask about running work, and the chat keeps the worktree open.
expect(mocks.close).toHaveBeenCalledWith(
'tab',
expect.objectContaining({
consentedPtyId: 'pty-a',
preserveWorktreeSelection: true,
onCancel: expect.any(Function)
})
)
exit.resolve({ wait: { satisfied: true, status: 'exited', exitCode: 0 } })
await expect(run).resolves.toBe(true)
}
)
it('leaves the tab and opens nothing when the ordinary close confirmation is cancelled', async () => {
mocks.close.mockImplementation((_tab, options) => options.onCancel())
const closing = vi.fn()
await expect(
closeCliChatResumeTerminal(source, () => true, hooks(closing), new AbortController().signal)
).resolves.toBe(false)
expect(closing).not.toHaveBeenCalled()
expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(0)
})
it.each([
{
satisfied: true,
status: 'exited',
exitCode: -1,
exitCause: { kind: 'unknown', reason: 'stop_unverified' }
},
{ satisfied: true, status: 'unknown', exitCode: null },
new Error('timeout')
])('goes on once an exit the host could not prove settles: %j', async (wait) => {
mocks.call.mockImplementation(async (_target, method, params) => {
const leaf = params.paneKey?.endsWith(':b') ? 'b' : 'a'
return method === 'terminal.resolvePane'
? {
terminal: { handle: `handle-${leaf}`, ptyId: `pty-${leaf}`, incarnationId: `inc-${leaf}` }
}
: wait instanceof Error
? Promise.reject(wait)
: { wait }
})
await expect(
closeCliChatResumeTerminal(source, () => true, hooks(), new AbortController().signal)
).resolves.toBe(true)
})
it('rechecks the source incarnation after an existing close dialog and says the close was dropped', async () => {
mocks.close.mockImplementation((_tab, options) => {
mocks.state.terminalPtyIncarnationsByPaneKey['tab:a'] = 'replacement'
expect(options.beforeClose()).toBe(false)
options.onCancel()
})
const closeHooks = hooks()
await expect(
closeCliChatResumeTerminal(source, () => true, closeHooks, new AbortController().signal)
).resolves.toBe(false)
expect(closeHooks.refused).toHaveBeenCalledOnce()
expect(closeHooks.closing).not.toHaveBeenCalled()
expect(mocks.call.mock.calls.filter((call) => call[1] === 'terminal.wait')).toHaveLength(0)
})
it('reports a vetoed confirmed close to its run even after the run was retired', async () => {
const controller = new AbortController()
let reenter: (() => boolean) | undefined
mocks.close.mockImplementation((_tab, options) => {
reenter = options.beforeClose
})
const closeHooks = hooks()
const run = closeCliChatResumeTerminal(source, () => true, closeHooks, controller.signal)
await vi.waitFor(() => expect(reenter).toBeDefined())
controller.abort()
await expect(run).resolves.toBe(false)
expect(reenter?.()).toBe(false)
// The run, not this helper, knows whether a newer continuation owns the confirmation.
expect(closeHooks.refused).toHaveBeenCalledOnce()
expect(closeHooks.closing).not.toHaveBeenCalled()
})
@@ -1,194 +0,0 @@
import type * as RuntimeCapabilityProofModule from '@/runtime/rpc/compatibility/runtime-capability-proof'
// @vitest-environment happy-dom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { CliChatResumeSource } from './cli-chat-resume-source'
import type * as FrameDrawnChatTabPlacementModule from '@/lib/frame-drawn-chat-tab-placement'
import type * as CloseTerminalModule from './cli-chat-resume-close-terminal'
const mocks = vi.hoisted(() => {
const state: { source: CliChatResumeSource | null } = { source: null }
return {
...state,
sourceCapability: vi.fn(),
closeCapability: vi.fn(),
capabilityState: vi.fn(),
closeTerminal: vi.fn(),
probe: vi.fn(),
createCapability: vi.fn(),
call: vi.fn(),
createSupport: vi.fn(),
toast: vi.fn(),
activate: vi.fn(async () => true),
frameDrawn: false
}
})
vi.mock('./cli-chat-resume-close-terminal', async (importOriginal) => ({
...(await importOriginal<typeof CloseTerminalModule>()),
closeCliChatResumeTerminal: mocks.closeTerminal
}))
vi.mock('./cli-chat-resume-source', () => ({ resolveCliChatResumeSource: () => mocks.source }))
vi.mock('../terminal/pty-running-work-probe', () => ({ probePtyRunningWork: mocks.probe }))
vi.mock(
'../../runtime/native-chat/host-capabilities/structured-agent-session-host-support',
() => ({
structuredAgentSessionHostSupports: mocks.closeCapability,
structuredAgentSessionHostCapabilityState: async (...args: unknown[]) =>
(await mocks.capabilityState(...args)) ??
((await mocks.closeCapability(...args)) ? 'supported' : 'unsupported'),
supportsStructuredAgentSessionCliSource: mocks.sourceCapability,
supportsStructuredAgentSessionCreateMessage: mocks.createCapability
})
)
vi.mock('../../runtime/native-chat/requests/structured-agent-session-call', () => ({
callStructuredAgentSession: (...args: unknown[]) =>
args[1] === 'agentSession.createSupport' ? mocks.createSupport(args[2]) : mocks.call(...args)
}))
vi.mock('@/runtime/native-chat/tab-inventory/structured-session-tab-inventory', () => ({
readStructuredSessionTabInventory: async () => {
throw new Error('Reply unavailable')
}
}))
vi.mock('@/lib/agent-session/launch/structured-agent-session-create-hydration', () => ({
publishStructuredAgentSessionCreateHydration: vi.fn()
}))
vi.mock('sonner', () => ({ toast: { error: mocks.toast } }))
// A frame-drawn server workspace's create carries the tab's place, read as it is sent.
vi.mock('@/lib/frame-drawn-chat-tab-placement', async (importOriginal) => {
const actual = await importOriginal<typeof FrameDrawnChatTabPlacementModule>()
return {
...actual,
withFrameDrawnChatTabPlacement: (
intent: Parameters<typeof actual.withFrameDrawnChatTabPlacement>[0]
) =>
mocks.frameDrawn
? { ...intent.params, tabPlacement: { groupId: 'g-1' } }
: actual.withFrameDrawnChatTabPlacement(intent)
}
})
vi.mock('@/lib/activate-ai-vault-structured-session', () => ({
activateAiVaultStructuredSession: mocks.activate
}))
// Switch-on, main opens the chat's tab and its frame draws it.
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', async (importOriginal) => ({
...(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeRpcClientWithLayoutApply(await importOriginal())
}))
vi.mock('@/runtime/rpc/compatibility/runtime-capability-proof', async (importOriginal) => ({
...(await importOriginal<typeof RuntimeCapabilityProofModule>()),
runtimeEnvironmentSupportsCapability: async () => true
}))
vi.mock('@/runtime/workspace-layout/frames/runtime-layout-client', async (importOriginal) =>
(
await import('@/runtime/workspace-layout/testing/layout-apply-test-transport.test-fixture')
).runtimeLayoutClientWithTestFrames(await importOriginal())
)
import { useAppStore } from '@/store'
import { getStructuredAgentSessionLaunchLifecycle } from '@/lib/agent-session/launch/structured-agent-session-launch-registry'
import { startStructuredAgentLaunch } from '@/lib/agent-session/launch/structured-agent-session-launch'
import { resolveWebSessionVisibleTabId } from '@/runtime/web-session-tabs-sync/navigation/web-session-focus-intent'
import {
drawTabsFromMain,
type TabsDrawnFromMain
} from '@/store/slices/tabs/tabs-drawn-from-main.test-fixture'
import { runCliChatResume } from './cli-chat-resume-run'
import {
SOURCE,
refuse,
resetCliChatResumeRun,
showAgentInSource,
tabs
} from './cli-chat-resume-run.test-fixture'
const creates = () => mocks.call.mock.calls.filter(([, method]) => method === 'agentSession.create')
let main: TabsDrawnFromMain | undefined
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
main?.close()
main = undefined
})
beforeEach(async () => {
resetCliChatResumeRun(mocks)
mocks.createSupport.mockResolvedValue({ supported: true })
main = await drawTabsFromMain(useAppStore)
})
describe('close terminal then continue on capable hosts', () => {
beforeEach(() => {
mocks.closeCapability.mockResolvedValue(true)
showAgentInSource()
})
it('leaves a tab the user picked while the chat waited on the close', async () => {
mocks.closeTerminal.mockImplementation(async (_source, _current, hooks) => {
useAppStore.getState().createUnifiedTab('wt-1', 'agent-session', {
id: 'picked',
entityId: 'picked-chat'
})
expect(resolveWebSessionVisibleTabId(useAppStore.getState(), 'wt-1')).toBe('picked')
hooks.prepared()
hooks.closing()
mocks.source = null
return true
})
await runCliChatResume(SOURCE)
await main?.settle()
expect(creates()).toHaveLength(1)
expect(resolveWebSessionVisibleTabId(useAppStore.getState(), 'wt-1')).toBe('picked')
})
it('starts the chat anew when the closed terminal never saved its conversation', async () => {
const answer = mocks.call.getMockImplementation()
mocks.call.mockImplementationOnce(async (_target, method) => {
expect(method).toBe('agentSession.create')
return { ok: false, refusal: refuse('transcriptNotFound') }
})
await runCliChatResume(SOURCE)
await vi.waitFor(() => expect(creates()).toHaveLength(2))
const [first, second] = creates().map(([, , params]) => params)
expect(first.resumeFrom?.providerSessionId).toBe(SOURCE.providerSessionId)
expect(second.resumeFrom).toBeUndefined()
expect(second.envelope.sessionId).toBe(first.envelope.sessionId)
mocks.call.mockImplementation(answer!)
await main?.settle()
expect(tabs().map((tab) => tab.entityId)).toEqual([first.envelope.sessionId])
expect(mocks.toast).not.toHaveBeenCalled()
})
// Joining it would re-send an unconfirmed chat's create beside the still-running CLI.
it.each(['pending', 'visibility-unknown'])(
'shows a %s chat already opening this conversation and keeps the terminal',
async (lifecycle) => {
// Its create never answers, or its reply is lost and the host can't be asked whether it exists.
const answer = mocks.call.getMockImplementation()
mocks.call.mockImplementation((...args: unknown[]) =>
args[1] !== 'agentSession.create'
? answer?.(...args)
: lifecycle === 'pending'
? new Promise(() => undefined)
: Promise.reject(new Error('response lost'))
)
const other = startStructuredAgentLaunch('wt-1', 'claude', {
requestId: 'other-resume',
resumeFrom: { providerSessionId: SOURCE.providerSessionId }
})
await vi.waitFor(() => {
expect(creates().length).toBeGreaterThan(0)
expect(getStructuredAgentSessionLaunchLifecycle('wt-1', other.sessionId)).toBe(lifecycle)
})
const sent = creates().length
await runCliChatResume(SOURCE, true)
await main?.settle()
expect(mocks.closeTerminal).not.toHaveBeenCalled()
expect(tabs().map((tab) => tab.entityId)).toEqual([other.sessionId])
expect(creates()).toHaveLength(sent)
expect(mocks.toast).not.toHaveBeenCalled()
}
)
})
@@ -1,48 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
buildTabAgentLaunchOptions,
buildTabAgentLaunchOptionsFromRows,
findMatchingTabAgentLaunchOptions
} from './tab-agent-launch-options'
describe('tab agent launch options', () => {
it('ranks an exact alias above weaker prefix matches', () => {
const options = buildTabAgentLaunchOptions(['codebuff', 'codex', 'copilot'], {
codebuff: 'codex-tools'
})
// The weaker codex-tools prefix starts first, so exact codex must move ahead.
expect(findMatchingTabAgentLaunchOptions('codex', options)[0]?.agent).toBe('codex')
expect(findMatchingTabAgentLaunchOptions('co', options).map((o) => o.agent)).toEqual(
expect.arrayContaining(['codex', 'copilot', 'codebuff'])
)
})
it('does not match on a mid-string substring that would hijack file results', () => {
const options = buildTabAgentLaunchOptions(['opencode', 'claude'])
// Agent rows outrank files, so broad mid-string hits must not hijack the result list.
expect(findMatchingTabAgentLaunchOptions('ode', options)).toEqual([])
})
})
it('projects the same CLI label, unavailable reason and stable chat ID as static rows', () => {
const unavailable = buildTabAgentLaunchOptionsFromRows([
{ kind: 'chat-unavailable', agent: 'claude', reason: 'ssh' },
{ kind: 'cli', agent: 'claude' },
{ kind: 'cli', agent: 'codex', chat: true }
])
expect(unavailable).toMatchObject([
{ id: 'chat:claude', label: 'Claude', reason: 'No chat over SSH', disabled: true },
{ id: 'cli:claude', label: 'Claude (CLI)', disabled: false },
{ id: 'cli:codex', label: 'Codex (CLI)', disabled: false }
])
// Typing the agent's name and pressing Enter launches its CLI, not the disabled chat.
expect(findMatchingTabAgentLaunchOptions('claude', unavailable)[0]?.id).toBe('cli:claude')
expect(
findMatchingTabAgentLaunchOptions('codex', unavailable).map((option) => [
option.id,
option.row?.kind
])
).toEqual([['cli:codex', 'cli']])
})
@@ -1,39 +0,0 @@
import { afterEach, expect, it, vi } from 'vitest'
const requestEditorFileClose = vi.hoisted(() => vi.fn<(fileId: string) => void>())
vi.mock('../editor/autosave/editor-autosave', () => ({ requestEditorFileClose }))
import { useAppStore } from '../../store'
import { makeOpenFile } from '../../store/slices/editor/types/open-file.test-fixture'
import { makeUnifiedTab } from '../../store/slices/tabs/tab-group.test-fixture'
import { registerEditorFrameFlush } from '../editor/save/flush/editor-pending-flush'
import { createWorkspaceTabCloseCommands } from './workspace-tab-close-commands'
const worktreeId = 'wt'
const tabOf = (entityId: string) =>
makeUnifiedTab({ id: 'tab', worktreeId, groupId: 'g', entityId, contentType: 'editor' })
const drainMicrotasks = () => new Promise((resolve) => setImmediate(resolve))
let removeFrame = () => {}
afterEach(() => removeFrame())
// Why: a rename keeps the tab id but moves its entity while the frame is flushing.
it('closes the renamed file, prompting when it is dirty, after the frame flush', async () => {
let answer: (flushed: boolean) => void = () => {}
removeFrame = registerEditorFrameFlush('old', () => new Promise((resolve) => (answer = resolve)))
useAppStore.setState({
openFiles: [makeOpenFile({ id: 'old', worktreeId })],
unifiedTabsByWorktree: { [worktreeId]: [tabOf('old')] }
})
createWorkspaceTabCloseCommands({ worktreeId, groupTabs: [tabOf('old')] }).closeItem('tab')
useAppStore.setState({
openFiles: [makeOpenFile({ id: 'new', worktreeId, isDirty: true })],
unifiedTabsByWorktree: { [worktreeId]: [tabOf('new')] }
})
answer(true)
await drainMicrotasks()
expect(requestEditorFileClose).toHaveBeenCalledWith('new', { tabId: 'tab' })
expect(useAppStore.getState().unifiedTabsByWorktree[worktreeId]).toHaveLength(1)
})
@@ -1,123 +0,0 @@
// @vitest-environment happy-dom
import { useState, type ComponentProps } from 'react'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { afterEach, expect, it, vi } from 'vitest'
import type { TaskPageComposerActionsModel } from '../use-task-page-composer-actions'
import type { TaskPageJiraBoardView } from './task-page-jira-board-view'
import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context'
import { defaultJiraListColumnIds, visibleJiraListColumns } from '../../jira-list-columns'
import { bumpProviderRuntimeSessionGeneration } from '@/runtime/hosts/observations/provider-runtime-context'
import { TaskPageJiraContent } from './Content'
import type * as I18n from '@/i18n/i18n'
type BoardProps = ComponentProps<typeof TaskPageJiraBoardView>
vi.mock('@/components/task-page/jira/task-page-jira-board-view', () => ({
TaskPageJiraBoardView: ({ target, scopeKey }: BoardProps) => {
const [draft, setDraft] = useState('')
return (
<div>
<input
aria-label="Pending board comment"
value={draft}
onChange={(event) => setDraft(event.target.value)}
/>
<output data-testid="board-owner">{JSON.stringify(target)}</output>
<output data-testid="board-scope">{scopeKey}</output>
</div>
)
}
}))
vi.mock('@/components/JiraIssueWorkspace', () => ({ default: () => null }))
vi.mock('@/components/task-page/linear/Content', () => ({ TaskPageLinearContent: () => null }))
vi.mock('@/components/jira-list-columns-menu', () => ({ JiraListColumnsMenu: () => null }))
vi.mock('@/i18n/i18n', async (importOriginal) => ({
...(await importOriginal<typeof I18n>()),
translate: (_key: string, fallback: string) => fallback
}))
afterEach(cleanup)
const source: TaskSourceContext = {
kind: 'task-source',
provider: 'jira',
projectId: 'content-owner-project',
hostId: 'runtime:explicit-jira-owner'
}
function model(sourceContext: TaskSourceContext | null): TaskPageComposerActionsModel {
const columns = defaultJiraListColumnIds()
const fixture = {
jiraStatus: { credentialError: null },
jiraHasWorkspace: false,
getJiraIssueWorkspaces: () => [],
jiraStatusReady: true,
jiraConnected: true,
selectedJiraSiteId: 'site-a',
hideTaskSource: vi.fn(),
taskSource: 'jira',
closeTaskDetailPage: vi.fn(),
selectedJiraIssue: null,
jiraDetailSourceContext: sourceContext,
openJiraDetailPage: vi.fn(),
jiraIssues: [],
jiraLoading: false,
jiraError: null,
jiraErrorDetailsOpen: false,
setJiraErrorDetailsOpen: vi.fn(),
jiraJqlRejection: null,
jiraSearchInput: '',
jiraOrderBy: 'updated',
jiraOrderDirection: 'desc',
handleJiraSort: vi.fn(),
jiraColumnIds: columns,
jiraColumns: visibleJiraListColumns(columns),
toggleJiraColumn: vi.fn(),
displayedJiraIssues: [],
displayedJiraStatusOrder: null,
sortedJiraIssues: [],
setJiraConnectOpen: vi.fn(),
handleUseJiraItem: vi.fn(),
jiraViewMode: 'board',
setJiraViewMode: vi.fn(),
jiraCurrentSprint: true,
setJiraCurrentSprint: vi.fn(),
jiraTaskSourceContext: sourceContext,
jiraTaskSourceScopeKey: 'content-source-scope',
accountBackedTaskSourceHostId: 'runtime:account-jira-owner',
providerRuntimeContextKey: 'runtime:unrelated-ui-a#0',
setJiraRefreshNonce: vi.fn()
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This presentation fixture supplies every field read by the Jira content branch.
return fixture as unknown as TaskPageComposerActionsModel
}
it.each([
{ label: 'explicit', sourceContext: source, owner: 'explicit-jira-owner' },
{ label: 'default', sourceContext: null, owner: 'account-jira-owner' }
])(
'keeps the $label Jira owner draft through unrelated focus and clears it for a new session',
({ sourceContext, owner }) => {
const current = model(sourceContext)
const { rerender } = render(<TaskPageJiraContent model={current} />)
expect(screen.getByTestId('board-owner').textContent).toBe(
JSON.stringify({ kind: 'environment', environmentId: owner })
)
const initialScope = screen.getByTestId('board-scope').textContent
fireEvent.change(screen.getByRole('textbox', { name: 'Pending board comment' }), {
target: { value: 'Keep this draft' }
})
current.providerRuntimeContextKey = 'runtime:unrelated-ui-b#0'
rerender(<TaskPageJiraContent model={current} />)
expect(screen.getByDisplayValue('Keep this draft')).toBeDefined()
expect(screen.getByTestId('board-scope').textContent).toBe(initialScope)
bumpProviderRuntimeSessionGeneration()
rerender(<TaskPageJiraContent model={current} />)
expect(screen.queryByDisplayValue('Keep this draft')).toBeNull()
expect(screen.getByTestId('board-scope').textContent).not.toBe(initialScope)
expect(screen.getByTestId('board-owner').textContent).toBe(
JSON.stringify({ kind: 'environment', environmentId: owner })
)
}
)
@@ -1,53 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { JiraIssue } from '../../../../../shared/jira/jira-types'
import type { TaskSourceContext } from '../../../../../shared/work-items/task-source-context'
import { readLinkedJiraIssues } from './task-page-jira-linked-issues'
const source: TaskSourceContext = {
kind: 'task-source',
provider: 'jira',
projectId: 'app',
hostId: 'runtime:remote'
}
const issue: JiraIssue = {
id: '1',
key: 'APP-1',
title: 'Fix login',
siteId: 'a',
url: 'https://a.example/browse/APP-1',
project: { id: '1', key: 'APP', name: 'Application' },
issueType: { id: '1', name: 'Bug' },
status: { id: '1', name: 'Open', categoryKey: 'new', categoryName: 'Open' },
labels: [],
createdAt: '',
updatedAt: ''
}
describe('Jira Has Workspace issue reads', () => {
it('keeps successful reads when another site fails and reports the failure', async () => {
const search = vi
.fn()
.mockResolvedValueOnce([issue])
.mockRejectedValueOnce(new Error('Site unavailable'))
const result = await readLinkedJiraIssues(
[
{ key: 'APP-1', siteId: 'a' },
{ key: 'APP-2', siteId: 'b' }
],
search,
source,
false
)
expect(result.issues).toEqual([issue])
expect(result.error).not.toBeNull()
})
it('does not accept a same-key result from the wrong Jira site', async () => {
const search = vi.fn().mockResolvedValue([{ ...issue, siteId: 'other' }])
const result = await readLinkedJiraIssues(
[{ key: 'APP-1', siteId: 'a' }],
search,
source,
false
)
expect(result.issues).toEqual([])
expect(result.error).not.toBeNull()
})
})
@@ -1,187 +0,0 @@
// @vitest-environment happy-dom
import {
reads,
task,
store,
source,
useRoutingFixture
} from './task-page-linear-refresh-test-fixtures'
import { reads as issueReadRegistry } from '@/store/slices/linear/linear-issue-read-lifecycle'
import { pendingLinearIssueWrites } from '@/store/slices/linear/linear-issue-publication'
import { useLinearIssueCreationForm } from './use-task-page-linear-creation-state'
import { useTaskPageLinearIssueCreation } from './use-task-page-linear-issue-creation'
import { useTaskPageJiraCreationStatePrelude } from '../jira/use-task-page-jira-creation-state'
import { useLinearIssueWorkspaceDetail } from '../../linear-issue-workspace-detail-state'
import { useAppStore } from '@/store'
import { writeLinearIssue } from '@/lib/work-items/linear/linear-issue-write'
import {
getProviderRuntimeContextKey,
bumpProviderRuntimeSessionGeneration
} from '@/runtime/hosts/observations/provider-runtime-context'
import type { LinearIssue } from '../../../../../shared/linear/issue-types'
import { expect, it, vi } from 'vitest'
import { act, renderHook, waitFor } from '@testing-library/react'
import { deferred } from '../../../store/slices/linear/linear-slice-test-harness'
function useCreateFixture(
context: ReturnType<typeof source>,
initial: LinearIssue | null = null,
initialTitle = 'Created',
initialOpen = true,
runtime = { current: 'runtime' }
) {
const draft = useAppStore.getState().newLinearIssueDraft
const noop = vi.fn()
const form = useLinearIssueCreationForm(runtime.current, {
open: initialOpen,
title: draft?.title ?? initialTitle,
body: draft?.body ?? (initialTitle ? 'Body' : '')
})
const route = useRoutingFixture(context, initial)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this fixture supplies the real consumer's exercised fields and actions; unrelated full-page/provider services are intentionally absent.
const creation = useTaskPageLinearIssueCreation({
...route,
settings: null,
providerRuntimeContextKey: runtime.current,
providerRuntimeContextKeyRef: runtime,
linearTaskSourceContext: context,
setLinearRefreshNonce: noop,
selectedLinearProject: null,
...form,
newLinearIssueTargetTeam: { id: 'team-1', workspaceId: 'w' }
} as never)
return {
...creation,
submitting: form.newLinearIssueSubmitting,
title: form.newLinearIssueTitle,
body: form.newLinearIssueBody,
open: form.newLinearIssueOpen
}
}
it('create selects N before pending A settles, without waiting for N follow-up hydration', async () => {
const s = store(),
context = source('local')
s.setState({ recordFeatureInteraction: vi.fn(), jiraIssueCache: {}, jiraSearchCache: {} })
const pending = deferred<{ ok: boolean }>(),
held = deferred<LinearIssue | null>()
const created = {
...task('Created N'),
id: 'N',
identifier: 'ENG-2',
title: 'Created title',
priority: 2
}
reads.create.mockResolvedValue({ ok: true, id: 'N', identifier: 'ENG-2' })
reads.detail.mockImplementation((_context, id) =>
id === 'N' && reads.detail.mock.calls.filter((call) => call[1] === 'N').length === 1
? Promise.resolve(created)
: held.promise
)
const hook = renderHook(() => {
const creation = useCreateFixture(context, task())
const detail = useLinearIssueWorkspaceDetail({
issue: creation.selectedLinearIssue ?? task(),
providerSettings: context,
requestKey: creation.selectedLinearIssue?.id ?? 'A'
})
return { ...creation, detail }
})
let saving!: Promise<{ ok: boolean }>
act(() => {
saving = writeLinearIssue(task(), { priority: 4 }, context, () => pending.promise)
})
await act(async () => {
await hook.result.current.handleCreateNewLinearIssue()
})
await waitFor(() => expect(hook.result.current.selectedLinearIssue?.id).toBe('N'))
expect(hook.result.current.detail.displayed).toMatchObject({
id: 'N',
title: 'Created title',
priority: 2,
workspaceId: 'w'
})
await act(async () => {
pending.resolve({ ok: false })
await saving
})
expect(hook.result.current.detail.displayed).toMatchObject({
id: 'N',
title: 'Created title',
priority: 2,
workspaceId: 'w'
})
expect(hook.result.current.detail.editState.priority).toBe(2)
expect(hook.result.current.detail.issueLoading).toBe(true)
hook.unmount()
held.resolve(null)
await held.promise
expect(pendingLinearIssueWrites.size).toBe(0)
expect(issueReadRegistry.size).toBe(0)
})
it('actual runtime replacement and new create outlive old success and own finally without revival', async () => {
const s = store(),
context = source('local'),
runtime = { current: getProviderRuntimeContextKey(null) }
s.setState({ recordFeatureInteraction: vi.fn(), jiraIssueCache: {}, jiraSearchCache: {} })
const old = deferred<{ ok: boolean; id: string; identifier: string }>(),
next = deferred<{ ok: boolean; id: string; identifier: string }>()
reads.create.mockReturnValueOnce(old.promise).mockReturnValueOnce(next.promise)
const hook = renderHook(() => {
const model = useCreateFixture(context, null, 'Old', true, runtime)
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the actual runtime reset prelude uses these Linear fields; unrelated Jira/metadata services are inert.
useTaskPageJiraCreationStatePrelude({
...model,
setNewLinearIssueTeamId: vi.fn(),
setNewLinearIssueProjects: vi.fn(),
setNewLinearIssueProjectsLoading: vi.fn()
} as never)
return model
})
let a!: Promise<void>, b!: Promise<void>
act(() => {
a = hook.result.current.handleCreateNewLinearIssue()
})
act(() => {
bumpProviderRuntimeSessionGeneration()
runtime.current = getProviderRuntimeContextKey(null)
hook.rerender()
})
expect(hook.result.current.submitting).toBe(false)
act(() => {
hook.result.current.setNewLinearIssueTitle('Replacement')
hook.result.current.setNewLinearIssueBody('New body')
hook.result.current.setNewLinearIssueOpen(true)
})
act(() => {
b = hook.result.current.handleCreateNewLinearIssue()
})
expect(hook.result.current.submitting).toBe(true)
await act(async () => {
old.resolve({ ok: true, id: 'Old', identifier: 'W-1' })
await a
})
expect(hook.result.current).toMatchObject({
title: 'Replacement',
body: 'New body',
open: true,
submitting: true
})
expect(reads.detail).not.toHaveBeenCalled()
await act(async () => {
next.resolve({ ok: false, id: 'New', identifier: 'W-2' })
await b
})
expect(hook.result.current.submitting).toBe(false)
act(() => hook.result.current.setNewLinearIssueOpen(false))
expect(s.getState().newLinearIssueDraft).toEqual({ title: 'Replacement', body: 'New body' })
hook.unmount()
expect(pendingLinearIssueWrites.size).toBe(0)
expect(issueReadRegistry.size).toBe(0)
act(() => s.getState().patchLinearIssue('Old', { priority: 4 }, { sourceContext: context }))
expect(reads.detail).not.toHaveBeenCalled()
})
@@ -1,10 +1,7 @@
import { describe, expect, it } from 'vitest'
import type { CacheEntry } from '@/store/github/cache/cache-model'
import type { GitHubWorkItem } from '../../../../shared/github/work-item-types'
import {
reconcileTaskPagePagesAfterLandingRefresh,
reconcileTaskPagePagesWithWorkItemsCache
} from './task-page-cache-selectors'
import { reconcileTaskPagePagesWithWorkItemsCache } from './task-page-cache-selectors'
function entry<T>(data: T): CacheEntry<T> {
return { data, fetchedAt: 1 }
@@ -28,18 +25,4 @@ describe('task page cache selectors', () => {
expect(nextPages[0]?.map((item) => item.repoHostId)).toEqual(['local', 'ssh:builder'])
expect(nextPages[0]?.[1]).toBe(remote)
})
it('replaces GitHub landing refresh rows when membership changes', () => {
const first = workItem('issue-1', 'repo-1')
const second = workItem('issue-2', 'repo-1')
const third = workItem('issue-3', 'repo-1')
const older = workItem('issue-4', 'repo-1')
const nextPages = reconcileTaskPagePagesAfterLandingRefresh(
[[first, second], [older]],
[third, first]
)
expect(nextPages).toEqual([[third, first]])
})
})
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
readTerminalPathExistence,
startTerminalPathExistsProbe,
writeTerminalPathExistence,
type TerminalPathExistsCache
} from './terminal-path-exists-cache'
describe('terminal path-exists cache', () => {
it('keeps expired negatives as ordering guards for older in-flight probes', () => {
const cache: TerminalPathExistsCache = new Map()
const older = startTerminalPathExistsProbe(1000)
const newer = startTerminalPathExistsProbe(2000)
writeTerminalPathExistence(cache, 'k', false, newer)
expect(readTerminalPathExistence(cache, 'k', 12_000)).toBeUndefined()
writeTerminalPathExistence(cache, 'k', true, older)
expect(cache.get('k')).toEqual({ exists: false, ...newer })
const latest = startTerminalPathExistsProbe(12_000)
writeTerminalPathExistence(cache, 'k', true, latest)
expect(readTerminalPathExistence(cache, 'k', 12_000)).toBe(true)
})
it('ignores an older probe result that lands after a newer one', () => {
const cache: TerminalPathExistsCache = new Map()
const older = startTerminalPathExistsProbe(1000)
const newer = startTerminalPathExistsProbe(2000)
writeTerminalPathExistence(cache, 'k', true, newer)
writeTerminalPathExistence(cache, 'k', false, older)
expect(cache.get('k')).toEqual({ exists: true, ...newer })
const latest = startTerminalPathExistsProbe(3000)
writeTerminalPathExistence(cache, 'k', false, latest)
expect(cache.get('k')).toEqual({ exists: false, ...latest })
})
it('orders overlapping probes that start in the same millisecond', () => {
const cache: TerminalPathExistsCache = new Map()
const older = startTerminalPathExistsProbe(1000)
const newer = startTerminalPathExistsProbe(1000)
writeTerminalPathExistence(cache, 'newer-first', false, newer)
writeTerminalPathExistence(cache, 'newer-first', true, older)
expect(cache.get('newer-first')).toEqual({ exists: false, ...newer })
writeTerminalPathExistence(cache, 'older-first', false, older)
writeTerminalPathExistence(cache, 'older-first', true, newer)
expect(cache.get('older-first')).toEqual({ exists: true, ...newer })
})
})
@@ -16,10 +16,7 @@ import {
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import {
createInitialStoreState,
buildActiveRuntimeEnvironmentState
} from '../test-fixtures/pty-connection-test-store-fixtures'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
@@ -36,11 +33,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
// Why: activeRuntimeEnvironmentId exercises the remote-runtime path where the renderer still owns OSC 9999 status.
function enableActiveRuntimeEnvironment(environmentId = 'env-1'): void {
mockStoreState = buildActiveRuntimeEnvironmentState(mockStoreState, environmentId)
}
function notifyStoreSubscribers(): void {
for (const listener of storeSubscribers.slice()) {
listener(mockStoreState)
@@ -86,101 +78,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
}
}
it('omits byte-parser callbacks from the local transport options', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks)
)
expect(createdTransportOptions[0]).toBeDefined()
for (const callback of SIDE_EFFECT_PARSER_CALLBACKS) {
expect(createdTransportOptions[0]?.[callback]).toBeUndefined()
}
// Lifecycle callbacks stay on the transport; only side-effect parsing moves to the fact consumer.
expect(createdTransportOptions[0]?.onPtySpawn).toBeTypeOf('function')
expect(createdTransportOptions[0]?.onPtyExit).toBeTypeOf('function')
})
it('keeps byte-parser callbacks on remote-runtime transports', async () => {
enableMainAuthority()
enableActiveRuntimeEnvironment()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks2 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const { createRemoteRuntimePtyTransport } =
await import('../../pty-transport/remote-runtime/remote-runtime-pty-transport')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks2)
)
expect(createRemoteRuntimePtyTransport).toHaveBeenCalledWith('env-1', expect.any(Object))
for (const callback of SIDE_EFFECT_PARSER_CALLBACKS) {
expect(createdTransportOptions[0]?.[callback]).toBeTypeOf('function')
}
})
it('consumes pty:sideEffect facts with the live-path policy after spawn', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks3 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const handler =
await import('../../pty-transport/output/terminal-side-effect-facts-handler')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const pane = createPane(1)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks3)
)
const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void
onPtySpawn('pty-fact-1')
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-1',
seq: 10,
facts: [
{ kind: 'title', normalizedTitle: 'Codex working', rawTitle: 'Codex working' },
{ kind: 'bell' }
]
})
expect(deps.setRuntimePaneTitle).toHaveBeenCalledWith('tab-1', 1, 'Codex working')
expect(deps.markTerminalBell).toHaveBeenCalledTimes(1)
expect(deps.markTerminalBell).toHaveBeenCalledWith({
worktreeId: 'wt-1',
tabId: 'tab-1',
paneKey: makePaneKey('tab-1', LEAF_1)
})
expect(deps.dispatchNotification).not.toHaveBeenCalled()
vi.advanceTimersByTime(250)
expect(deps.dispatchNotification).toHaveBeenCalledWith(
expect.objectContaining({
source: 'terminal-bell',
paneKey: makePaneKey('tab-1', LEAF_1)
})
)
})
it('stops consuming facts after the pane binding is disposed', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
@@ -210,49 +107,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
expect(deps.markTerminalBell).not.toHaveBeenCalled()
})
it('schedules the completion notification for genuine working→idle facts', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks5 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const handler =
await import('../../pty-transport/output/terminal-side-effect-facts-handler')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const deps = createDeps()
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks5)
)
const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void
onPtySpawn('pty-fact-genuine')
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-genuine',
seq: 1,
facts: [
{ kind: 'title', normalizedTitle: '⠋ Codex working', rawTitle: '⠋ Codex working' },
{ kind: 'agent-working' }
]
})
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-genuine',
seq: 2,
facts: [
{ kind: 'title', normalizedTitle: '* Codex done', rawTitle: '* Codex done' },
{ kind: 'agent-idle', title: '* Codex done' }
]
})
vi.advanceTimersByTime(AGENT_TASK_COMPLETE_NOTIFICATION_MAX_WAIT_MS)
expect(deps.dispatchNotification).toHaveBeenCalledWith(
expect.objectContaining({ source: 'agent-task-complete' })
)
})
it('clears state without completion attention for stale-derived facts', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
@@ -306,82 +160,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
expect(deps.markTerminalBell).not.toHaveBeenCalled()
})
it('drops the agent status from a command-finished fact like the byte path did', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const handler =
await import('../../pty-transport/output/terminal-side-effect-facts-handler')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState.agentStatusByPaneKey = {
[paneKey]: {
paneKey,
state: 'done',
prompt: 'hi',
updatedAt: 1000,
stateStartedAt: 1000,
agentType: 'codex',
stateHistory: []
}
}
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks7)
)
const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void
onPtySpawn('pty-fact-133')
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-133',
seq: 1,
facts: [{ kind: 'command-finished', exitCode: 130 }]
})
expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey)
expect(mockStoreState.removeAgentStatus).not.toHaveBeenCalled()
})
it('routes pr-link facts to the worktree PR observer', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks8 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const handler =
await import('../../pty-transport/output/terminal-side-effect-facts-handler')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks8)
)
const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void
onPtySpawn('pty-fact-pr')
const link = {
url: 'https://github.com/acme/orca/pull/42',
slug: { owner: 'acme', repo: 'orca' },
number: 42
}
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-pr',
seq: 1,
facts: [{ kind: 'pr-link', link }]
})
expect(mockStoreState.observeTerminalGitHubPullRequestLink).toHaveBeenCalledWith(
'wt-1',
link,
expect.objectContaining({ tabId: 'tab-1', ptyId: 'tab-pty' })
)
})
it('does not byte-scan PR links or OSC 133 — facts are the only consumer', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
@@ -424,53 +202,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
expect(mockStoreState.dropAgentStatus).not.toHaveBeenCalled()
})
it('seeds and settles Command Code status from command-code facts', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks10 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const handler =
await import('../../pty-transport/output/terminal-side-effect-facts-handler')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
vi.useFakeTimers()
const paneKey = makePaneKey('tab-1', LEAF_1)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(createDeps() as never, agentTitleMocks10)
)
const onPtySpawn = createdTransportOptions[0]?.onPtySpawn as (ptyId: string) => void
onPtySpawn('pty-fact-cc')
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-cc',
seq: 1,
facts: [{ kind: 'command-code-working', prompt: 'say hi' }]
})
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'working',
prompt: 'say hi',
agentType: 'command-code'
})
// Done facts are hints; pane policy owns settling so it can consult the live row before completion.
handler._dispatchTerminalSideEffectBatchForTest({
ptyId: 'pty-fact-cc',
seq: 2,
facts: [{ kind: 'command-code-done', prompt: 'say hi' }]
})
vi.advanceTimersByTime(1499)
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({ state: 'working' })
vi.advanceTimersByTime(1)
expect(mockStoreState.agentStatusByPaneKey[paneKey]).toMatchObject({
state: 'done',
prompt: 'say hi',
agentType: 'command-code'
})
})
it('rejects Command Code facts when Claude owns the pane', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
@@ -614,38 +345,6 @@ export function registerPtyConnectionMainSideEffectAuthorityTests(): void {
})
})
it('does not byte-scan Command Code output — facts are the only consumer', async () => {
enableMainAuthority()
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks14 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const transport = createMockTransport()
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return 'pty-authority-cc-bytes'
}
)
transportFactoryQueue.push(transport)
connectPanePty(
createPane(1) as never,
createManager(1) as never,
bindPaneAgentTitleMocks(
createDeps({ startup: { command: 'command-code --trust' } }) as never,
agentTitleMocks14
)
)
await flushAsyncTicks()
expect(capturedDataCallback.current).not.toBeNull()
capturedDataCallback.current?.('# Command Code v0.27.2\r\n')
capturedDataCallback.current?.('❯ Fix the spinner\r\n\x1b[35m✻ Thinking...\x1b[0m')
expect(mockStoreState.setAgentStatus).not.toHaveBeenCalled()
})
it('honors the persisted kill switch for panes bound before settings hydrate', async () => {
// Pre-hydration: settings not loaded but kill switch persisted off — pane registers byte parsers, not a fact consumer.
mockStoreState.settings = null
@@ -1,141 +0,0 @@
import { bindPtyConnectionTestMocks } from '../test-fixtures/pty-connection-mocks.spec'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { makePaneKey } from '../../../../../../shared/workspace-layout/stable-pane-id'
import {
LEAF_1,
createMockTransport,
createPane,
createManager,
type MockTransport
} from '../test-fixtures/pty-connection-test-pane-fixtures'
import {
buildPaneConnectionDeps,
type PtyConnectionAgentTitleMocks,
bindPaneAgentTitleMocks
} from '../test-fixtures/pty-connection-test-deps'
import { createInitialStoreState } from '../test-fixtures/pty-connection-test-store-fixtures'
import type { StoreState } from '../test-fixtures/pty-connection-test-store-state'
import {
installTerminalTestGlobals,
restoreTerminalTestGlobals
} from '../test-fixtures/pty-connection-test-environment'
export function registerPtyConnectionBellQueryReplyAndStaleInputTests(): void {
let mockStoreState: StoreState
let transportFactoryQueue: MockTransport[] = []
let createdTransportOptions: Record<string, unknown>[] = []
let storeSubscribers: ((state: StoreState) => void)[] = []
function createDeps(overrides: Record<string, unknown> = {}) {
return buildPaneConnectionDeps(() => mockStoreState, overrides)
}
describe('connectPanePty', () => {
beforeEach(async () => {
vi.clearAllMocks()
transportFactoryQueue = []
createdTransportOptions = []
storeSubscribers = []
mockStoreState = createInitialStoreState(() => mockStoreState)
bindPtyConnectionTestMocks({
getState: () => mockStoreState,
getTransportQueue: () => transportFactoryQueue,
getTransportOptions: () => createdTransportOptions,
getStoreSubscribers: () => storeSubscribers,
setStoreSubscribers: (subscribers) => {
storeSubscribers = subscribers
}
})
await installTerminalTestGlobals()
})
afterEach(async () => {
await restoreTerminalTestGlobals()
})
it('forwards raw onData after a bell as a query reply', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks7 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const transport = createMockTransport()
transportFactoryQueue.push(transport)
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks7)
)
const bellHandler = createdTransportOptions[0]?.onBell as (() => void) | undefined
if (!bellHandler || !onDataHandler) {
throw new Error('expected bell and onData handlers to be registered')
}
bellHandler()
;(onDataHandler as (data: string) => void)('a')
expect(deps.markTerminalBell).toHaveBeenCalledWith({
worktreeId: 'wt-1',
tabId: 'tab-1',
paneKey: makePaneKey('tab-1', LEAF_1)
})
expect(transport.sendInput).toHaveBeenCalledWith('a', 'query-reply')
})
// Why: on a stale-codex pane (pending account-switch restart), production blocks sendInput.
it('blocks onData on a stale codex pane', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks8 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
const transport = createMockTransport('pty-codex-stale')
transportFactoryQueue.push(transport)
// isCodexPaneStale reads codexRestartNoticeByPtyId; seed a restart notice to trigger the stale branch.
mockStoreState = {
...mockStoreState,
tabsByWorktree: {
'wt-1': [{ id: 'tab-1', ptyId: 'pty-codex-stale' }]
},
ptyIdsByTabId: {
'tab-1': ['pty-codex-stale']
},
codexRestartNoticeByPtyId: {
'pty-codex-stale': { previousAccountLabel: 'A', nextAccountLabel: 'B' }
}
}
const pane = createPane(1)
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
const manager = createManager(1)
const deps = createDeps()
connectPanePty(
pane as never,
manager as never,
bindPaneAgentTitleMocks(deps as never, agentTitleMocks8)
)
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
;(onDataHandler as (data: string) => void)('a')
// Stale-codex input is also blocked from reaching the transport.
expect(transport.sendInput).not.toHaveBeenCalled()
})
})
}
@@ -165,69 +165,5 @@ export function registerPtyConnectionCommandFinishedInterruptArbitrationTests():
}
}
)
it('drops the command-finished status when pending interrupt inference is rejected', async () => {
const { connectPanePty } = await import('../connect-pane-pty')
const agentTitleMocks15 =
await vi.importMock<PtyConnectionAgentTitleMocks>('@/lib/agent-status')
vi.mocked(window.api.agentStatus.inferInterrupt).mockResolvedValue(false)
const capturedDataCallback: { current: ((data: string) => void) | null } = { current: null }
const transport = createMockTransport()
transport.connect.mockImplementation(
async ({ callbacks }: { callbacks: ConnectCallbacks }) => {
capturedDataCallback.current = callbacks.onData ?? null
return { id: 'tab-pty' }
}
)
transportFactoryQueue.push(transport)
vi.useFakeTimers()
vi.setSystemTime(1_100)
const paneKey = makePaneKey('tab-1', LEAF_1)
mockStoreState = {
...mockStoreState,
agentStatusByPaneKey: {
[paneKey]: {
paneKey,
state: 'working',
prompt: 'stop quickly',
updatedAt: 1_000,
stateStartedAt: 900,
agentType: 'custom-agent',
terminalTitle: 'Codex',
stateHistory: []
}
}
}
const terminalTarget = createKeyboardEventTarget()
const pane = createPane(1)
;(pane.terminal as { element?: unknown }).element = terminalTarget.target
let onDataHandler: ((data: string) => void) | null = null
pane.terminal.onData = vi.fn(((handler: (data: string) => void) => {
onDataHandler = handler
return { dispose: vi.fn() }
}) as typeof pane.terminal.onData)
connectPanePty(
...mockPanePtyArgs(
pane,
createManager(1),
bindPaneAgentTitleMocks(createDeps(), agentTitleMocks15)
)
)
vi.advanceTimersByTime(1_000)
await flushAsyncTicks()
if (!onDataHandler) {
throw new Error('expected onData handler to be registered')
}
terminalTarget.dispatch(keyEvent({ key: 'c', ctrlKey: true }))
;(onDataHandler as unknown as (data: string) => void)('\x03')
capturedDataCallback.current?.('\x1b]133;D;130\x07thebr ~/repo $ ')
await flushAsyncTicks()
expect(window.api.agentStatus.inferInterrupt).toHaveBeenCalled()
expect(mockStoreState.dropAgentStatus).toHaveBeenCalledWith(paneKey)
})
})
}

Some files were not shown because too many files have changed in this diff Show More