Merge remote-tracking branch 'origin/main' into brennanb2025/activity-tab-index-reuse

This commit is contained in:
Brennan Benson
2026-11-09 16:19:01 -08:00
415 changed files with 13342 additions and 11511 deletions
+1
View File
@@ -282,6 +282,7 @@
1 src/main/ipc/filesystem/watcher-process/parcel-watcher-supervisor-subscribe.ts
1 src/main/ipc/filesystem/watcher-process/rebinding-file-watch.ts
1 src/main/ipc/filesystem/watcher-process/watcher-event-root-path-rewrite.ts
1 src/main/ipc/floating-workspace-directory.ts
1 src/main/ipc/macos-keyboard-layout-snapshot.ts
1 src/main/ipc/notification-authorization-status.ts
1 src/main/ipc/pty/spawn-pane-env.ts
File diff suppressed because one or more lines are too long
@@ -24,6 +24,13 @@ import {
routePathnameFromKey
} from '../../mobile-web-app/mobile-web-app-route-manifest.mjs'
import { MOBILE_WEB_PAGE_ROUTES } from './mobile-web-page-routes.mjs'
import {
ROUTE_ENTRY_NAMESPACE,
entryStaticClosure,
isScriptOutput,
lazyModulesToAnchor,
sharedModulesToMerge
} from './mobile-web-app-chunk-grouping.mjs'
const projectDir = fileURLToPath(new URL('../../../..', import.meta.url))
const mobileDir = join(projectDir, 'mobile')
@@ -134,7 +141,7 @@ const HAIRLINE_PLUGIN_NAME = 'orca-hairline-device-pixel'
const ENTRY_CHUNK_NAME = 'entry'
const ROUTE_MANIFEST_MODULE = /web-entry[\\/]route-manifest(\.ts)?$/
const ROUTE_ENTRY_NAMESPACE = 'orca-route-entry'
const LAZY_ENTRY_NAMESPACE = 'orca-lazy-entry'
// The entry's static imports as written, minus the manifest: a route importing it would be an output cycle.
async function entryImportAnchors() {
@@ -160,8 +167,14 @@ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
// Keep typed route-manifest file for TS/Metro resolution; replace only its body for web.
// Routes import the entry's imports first, so esbuild keeps those modules in one chunk instead of one per route subset.
// Routes also import every module in sharedModules, which esbuild then puts in one chunk all routes load.
function routeManifestPlugin(manifestSource, routes, sharedModules) {
// Lazy modules in anchoredLazyModules (path to export names) get the same imports, so they don't split those chunks either.
function routeManifestPlugin(manifestSource, routes, sharedModules, anchoredLazyModules) {
let anchors
const anchoredImports = async () => {
anchors ??= entryImportAnchors()
const shared = sharedModules.map((module) => `import ${JSON.stringify(module)}\n`).join('')
return `${await anchors}${shared}`
}
return {
name: ROUTE_MANIFEST_PLUGIN_NAME,
setup(build) {
@@ -170,26 +183,43 @@ function routeManifestPlugin(manifestSource, routes, sharedModules) {
loader: 'js',
resolveDir: mobileDir
}))
if (routes.length === 0) {
return
}
const routeImport = new RegExp(
`^(?:${routes.map(({ module }) => escapeRegExp(module)).join('|')})$`
)
build.onResolve({ filter: routeImport }, (args) =>
args.kind === 'dynamic-import'
? { path: args.path, namespace: ROUTE_ENTRY_NAMESPACE }
: undefined
)
build.onLoad({ filter: /.*/, namespace: ROUTE_ENTRY_NAMESPACE }, async (args) => {
anchors ??= entryImportAnchors()
const shared = sharedModules.map((module) => `import ${JSON.stringify(module)}\n`).join('')
return {
contents: `${await anchors}${shared}export { default } from ${JSON.stringify(args.path)}\n`,
if (routes.length > 0) {
const routeImport = new RegExp(
`^(?:${routes.map(({ module }) => escapeRegExp(module)).join('|')})$`
)
build.onResolve({ filter: routeImport }, (args) =>
args.kind === 'dynamic-import'
? { path: args.path, namespace: ROUTE_ENTRY_NAMESPACE }
: undefined
)
build.onLoad({ filter: /.*/, namespace: ROUTE_ENTRY_NAMESPACE }, async (args) => ({
contents: `${await anchoredImports()}export { default } from ${JSON.stringify(args.path)}\n`,
loader: 'js',
resolveDir: dirname(entryPoint)
}))
}
if (anchoredLazyModules.size === 0) {
return
}
build.onResolve({ filter: /.*/ }, async (args) => {
if (args.kind !== 'dynamic-import' || args.pluginData === LAZY_ENTRY_NAMESPACE) {
return undefined
}
const { path, errors } = await build.resolve(args.path, {
kind: args.kind,
importer: args.importer,
resolveDir: args.resolveDir,
pluginData: LAZY_ENTRY_NAMESPACE
})
return errors.length === 0 && anchoredLazyModules.has(path)
? { path, namespace: LAZY_ENTRY_NAMESPACE }
: undefined
})
build.onLoad({ filter: /.*/, namespace: LAZY_ENTRY_NAMESPACE }, async (args) => ({
contents: `${await anchoredImports()}export { ${anchoredLazyModules.get(args.path).join(', ')} } from ${JSON.stringify(args.path)}\n`,
loader: 'js',
resolveDir: dirname(entryPoint)
}))
}
}
}
@@ -234,7 +264,11 @@ const hairlineDevicePixelPlugin = {
}
/** Split out so a test can read the options MOBILE_WEB_APP_SHIMS claims, without a build. */
export function mobileWebAppBuildOptions(routes, sharedModules = []) {
export function mobileWebAppBuildOptions(
routes,
sharedModules = [],
anchoredLazyModules = new Map()
) {
return {
// Fixed so no absolute path of this checkout can reach the output.
absWorkingDir: mobileDir,
@@ -267,7 +301,12 @@ export function mobileWebAppBuildOptions(routes, sharedModules = []) {
zod: MOBILE_ZOD_PACKAGE
},
plugins: [
routeManifestPlugin(renderMobileWebAppRouteManifest(routes), routes, sharedModules),
routeManifestPlugin(
renderMobileWebAppRouteManifest(routes),
routes,
sharedModules,
anchoredLazyModules
),
lucideBarrelPlugin,
hairlineDevicePixelPlugin
],
@@ -311,66 +350,6 @@ export function mobileWebAppBuildOptions(routes, sharedModules = []) {
}
}
// Budget entry plus transitive static imports, stopping at dynamic imports; entry-only limits let shared initial chunks grow unseen.
export function entryStaticClosure(metafile, entryOutputPath) {
const reached = new Set([entryOutputPath])
for (const current of reached) {
for (const imported of metafile.outputs[current]?.imports ?? []) {
if (imported.kind !== 'import-statement' || reached.has(imported.path)) {
continue
}
reached.add(imported.path)
}
}
return reached
}
// esbuild cuts a chunk per set of routes sharing a module; one this small costs more as a request than as code every route loads.
const MERGED_SHARED_CHUNK_MAX_BYTES = 16 * 1024
// Small route-shared chunks whose static imports already load at boot or merge too, so merging adds only their own bytes.
// ESM only: a bare import runs a CommonJS module's body at route load, not where its importer first needs it.
function sharedModulesToMerge(metafile, entryOutputPath) {
const { inputs, outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const routeReached = new Set(
Object.entries(outputs)
.filter(([, output]) => output.entryPoint?.startsWith(`${ROUTE_ENTRY_NAMESPACE}:`))
.flatMap(([path]) => [...entryStaticClosure(metafile, path)])
)
const merged = new Set(
Object.entries(outputs)
.filter(
([path, output]) =>
isScriptOutput(path) &&
!output.entryPoint &&
!boot.has(path) &&
routeReached.has(path) &&
output.bytes <= MERGED_SHARED_CHUNK_MAX_BYTES &&
Object.keys(output.inputs).every((input) => inputs[input]?.format === 'esm')
)
.map(([path]) => path)
)
const importsUnmerged = (path) =>
outputs[path].imports.some(
({ kind, path: imported }) =>
kind === 'import-statement' && !boot.has(imported) && !merged.has(imported)
)
for (let dropped = true; dropped;) {
dropped = false
for (const path of merged) {
if (importsUnmerged(path)) {
merged.delete(path)
dropped = true
}
}
}
return [...merged]
.flatMap((path) => Object.keys(outputs[path].inputs))
.sort()
.map((input) => resolve(mobileDir, input))
}
// Hash final output bytes leaf-first, rewriting dependency names before hashing importers.
// esbuild hashes checkout-dependent input paths; renaming makes manifest hashes/import URLs agree and avoids redownloading identical bundles across checkouts.
export function renameOutputsByContent(metafile, outputFiles) {
@@ -438,8 +417,6 @@ export function routeChunkNames(metafile, routes, renamed) {
)
}
const isScriptOutput = (path) => path.endsWith('.js')
// appDir is a seam for the tests, which bundle a scratch route tree; production always uses mobile/app.
// Page closure includes ancestor layouts as entry modules, not just route imports.
export async function mobileWebAppRouteClosure(routeModule) {
@@ -532,10 +509,12 @@ function entryOutput(metafile) {
// The page's scripts as shipped: a first build finds the small shared chunks, a second merges them.
export async function buildMobileWebAppScripts(routes) {
const split = await esbuild.build(mobileWebAppBuildOptions(routes))
const sharedModules = sharedModulesToMerge(split.metafile, entryOutput(split.metafile))
return sharedModules.length === 0
const entryOutputPath = entryOutput(split.metafile)
const sharedModules = sharedModulesToMerge(split.metafile, entryOutputPath)
const anchoredLazyModules = lazyModulesToAnchor(split.metafile, entryOutputPath)
return sharedModules.length === 0 && anchoredLazyModules.size === 0
? split
: esbuild.build(mobileWebAppBuildOptions(routes, sharedModules))
: esbuild.build(mobileWebAppBuildOptions(routes, sharedModules, anchoredLazyModules))
}
export async function bundleMobileWebApp({ appDir = defaultAppDir } = {}) {
@@ -599,7 +578,9 @@ export function resolveMobileWebPageRoutes(routeKeys, declared = MOBILE_WEB_PAGE
export async function buildMobileWebAppBundle({
appDir,
outDir = defaultOutDir,
pageRoutes = MOBILE_WEB_PAGE_ROUTES
pageRoutes = MOBILE_WEB_PAGE_ROUTES,
// Only the shipped tree pays for brotli-11; tests and verify's scratch builds read raw assets.
brotli = false
} = {}) {
const [
desktopVersion,
@@ -645,7 +626,8 @@ export async function buildMobileWebAppBundle({
written: [indexAsset, ...written],
desktopVersion,
protocolWindow,
routes: resolveMobileWebPageRoutes(routeKeys, pageRoutes)
routes: resolveMobileWebPageRoutes(routeKeys, pageRoutes),
brotli
})
return {
manifest,
@@ -670,7 +652,7 @@ if (isDirectInvocation(import.meta.url, process.argv[1])) {
}
try {
const { manifest, outDir, routeKeys, entryStaticBytes, chunkCount } =
await buildMobileWebAppBundle()
await buildMobileWebAppBundle({ brotli: true })
console.log(
`[build-mobile-web-app-bundle] OK — ${String(routeKeys.length)} route(s), ` +
`${String(chunkCount)} chunk(s), ${String(entryStaticBytes)} bytes before the first route, ` +
@@ -0,0 +1,102 @@
import { realpathSync } from 'node:fs'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const mobileDir = fileURLToPath(new URL('../../../../mobile', import.meta.url))
export const ROUTE_ENTRY_NAMESPACE = 'orca-route-entry'
export const isScriptOutput = (path) => path.endsWith('.js')
// Budget entry plus transitive static imports, stopping at dynamic imports; entry-only limits let shared initial chunks grow unseen.
export function entryStaticClosure(metafile, entryOutputPath) {
const reached = new Set([entryOutputPath])
for (const current of reached) {
for (const imported of metafile.outputs[current]?.imports ?? []) {
if (imported.kind !== 'import-statement' || reached.has(imported.path)) {
continue
}
reached.add(imported.path)
}
}
return reached
}
// esbuild cuts a chunk per set of routes sharing a module; one this small costs more as a request than as code every route loads.
const MERGED_SHARED_CHUNK_MAX_BYTES = 16 * 1024
// Small route-shared chunks whose static imports already load at boot or merge too, so merging adds only their own bytes.
// ESM only: a bare import runs a CommonJS module's body at route load, not where its importer first needs it.
export function sharedModulesToMerge(metafile, entryOutputPath) {
const { inputs, outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const routeReached = new Set(
Object.entries(outputs)
.filter(([, output]) => output.entryPoint?.startsWith(`${ROUTE_ENTRY_NAMESPACE}:`))
.flatMap(([path]) => [...entryStaticClosure(metafile, path)])
)
const merged = new Set(
Object.entries(outputs)
.filter(
([path, output]) =>
isScriptOutput(path) &&
!output.entryPoint &&
!boot.has(path) &&
routeReached.has(path) &&
output.bytes <= MERGED_SHARED_CHUNK_MAX_BYTES &&
Object.keys(output.inputs).every((input) => inputs[input]?.format === 'esm')
)
.map(([path]) => path)
)
const importsUnmerged = (path) =>
outputs[path].imports.some(
({ kind, path: imported }) =>
kind === 'import-statement' && !boot.has(imported) && !merged.has(imported)
)
for (let dropped = true; dropped;) {
dropped = false
for (const path of merged) {
if (importsUnmerged(path)) {
merged.delete(path)
dropped = true
}
}
}
return [...merged]
.flatMap((path) => Object.keys(outputs[path].inputs))
.sort()
.map((input) => resolve(mobileDir, input))
}
// A lazy module sharing boot code gives those modules a new importer set, so esbuild would split the boot chunks;
// anchor it like a route. Modules boot imports lazily (routes, catalogs) stay as they are: anchoring them is an output cycle.
// esbuild's runtime helper chunk has no inputs and every chunk imports it, so self-contained engines (mermaid) keep their bytes.
export function lazyModulesToAnchor(metafile, entryOutputPath) {
const { outputs } = metafile
const boot = entryStaticClosure(metafile, entryOutputPath)
const bootLoadsLazily = new Set(
[...boot].flatMap((path) =>
outputs[path].imports
.filter(({ kind }) => kind === 'dynamic-import')
.map(({ path: imported }) => imported)
)
)
const sharesBootModules = ({ imports }) =>
imports.some(
({ kind, path }) =>
kind === 'import-statement' &&
boot.has(path) &&
Object.keys(outputs[path].inputs).length > 0
)
return new Map(
Object.entries(outputs)
.filter(
([path, output]) =>
output.entryPoint &&
!boot.has(path) &&
!bootLoadsLazily.has(path) &&
sharesBootModules(output)
)
.map(([, output]) => [realpathSync(resolve(mobileDir, output.entryPoint)), output.exports])
)
}
@@ -15,7 +15,11 @@ const PIXEL_PNG = Buffer.from(
'base64'
)
export async function writeMobileWebBundleFixtureTree({ outDir, body = 'fixture' }) {
export async function writeMobileWebBundleFixtureTree({
outDir,
body = 'fixture',
brotli = false
}) {
const [desktopVersion, protocolWindow] = await Promise.all([
readDesktopVersion(),
readProtocolWindow()
@@ -49,6 +53,7 @@ export async function writeMobileWebBundleFixtureTree({ outDir, body = 'fixture'
image
],
desktopVersion,
protocolWindow
protocolWindow,
brotli
})
}
@@ -3,10 +3,13 @@ import { readFile, mkdir, rm, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { brotliCompress, constants as zlibConstants } from 'node:zlib'
const { darkBuildMarkers } = createRequire(import.meta.url)('../../../dark-build-switches.cjs')
const projectDir = fileURLToPath(new URL('../../../..', import.meta.url))
const brotliCompressAsync = promisify(brotliCompress)
export const MOBILE_WEB_BUNDLE_SCHEMA_VERSION = 1
export const MOBILE_WEB_BUNDLE_ENTRYPOINT = 'index.html'
@@ -101,6 +104,31 @@ export async function readDesktopVersion() {
return packageJson.version
}
// Mirrors mobileWebBundleBrotliPath in src/shared/mobile-web-bundle/manifest-contract.ts.
export function mobileWebBundleBrotliPath(assetPath) {
return `${assetPath}.br`
}
// Largest first so the slowest file starts first on zlib's thread pool; keep only copies that shrink.
async function compressWithBrotli(written) {
const largestFirst = [...written].sort((left, right) => right.byteLength - left.byteLength)
const copies = await Promise.all(
largestFirst.map((asset) =>
brotliCompressAsync(asset.bytes, {
params: {
[zlibConstants.BROTLI_PARAM_QUALITY]: zlibConstants.BROTLI_MAX_QUALITY,
[zlibConstants.BROTLI_PARAM_SIZE_HINT]: asset.byteLength
}
})
)
)
return new Map(
largestFirst.flatMap((asset, index) =>
copies[index].byteLength < asset.byteLength ? [[asset.path, copies[index]]] : []
)
)
}
// Single manifest producer keeps builder/contract/packaging guard shape aligned.
export async function writeMobileWebBundleTree({
outDir,
@@ -109,10 +137,22 @@ export async function writeMobileWebBundleTree({
protocolWindow,
// Empty route list makes shell render every screen natively.
routes = [],
// Whole-file brotli copies for phones that inflate natively.
brotli = false,
env = process.env
}) {
const brotliCopies = brotli ? await compressWithBrotli(written) : new Map()
const assets = written
.map(({ path, sha256, byteLength, contentType }) => ({ path, sha256, byteLength, contentType }))
.map(({ path, sha256, byteLength, contentType }) => {
const copy = brotliCopies.get(path)
return {
path,
sha256,
byteLength,
contentType,
...(copy === undefined ? {} : { brotliByteLength: copy.byteLength })
}
})
.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))
const manifest = {
schemaVersion: MOBILE_WEB_BUNDLE_SCHEMA_VERSION,
@@ -133,6 +173,9 @@ export async function writeMobileWebBundleTree({
for (const asset of written) {
await writeFile(join(outDir, asset.path), asset.bytes)
}
for (const [path, copy] of brotliCopies) {
await writeFile(join(outDir, mobileWebBundleBrotliPath(path)), copy)
}
await writeFile(join(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
// Keep switch metadata outside manifest so compiled page bytes/buildId remain unchanged.
for (const marker of darkBuildMarkers(env)) {
@@ -5885,7 +5885,6 @@
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-restored-baseline-shortfall.test.ts": 1902,
"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-spawn-and-startup.test.ts": 19652,
"src/renderer/src/components/terminal-pane/pty-connection/spawn/pty-connection-spawn-deferred-sleep.test.ts": 6918,
"src/renderer/src/components/terminal-pane/pty-connection/startup/pty-connection-split-cwd-resolution.test.ts": 2139,
"src/renderer/src/components/terminal-pane/pty-connection/tests/pty-connection-visibility-and-exit.test.ts": 18950,
"src/renderer/src/components/terminal-pane/pty-connection/output-restore/pty-connection-visible-pane-output-pause-latch.test.ts": 1639,
"src/renderer/src/components/terminal-pane/pty-connection/reattach/deferred-session-reattach-newer-daemon-hold.test.ts": 2570,
@@ -1,6 +1,7 @@
const { createHash } = require('node:crypto')
const { readFileSync, readdirSync, statSync } = require('node:fs')
const { join, resolve } = require('node:path')
const { brotliDecompressSync } = require('node:zlib')
const { darkBuildMarkerFileNames } = require('../../../dark-build-switches.cjs')
@@ -98,6 +99,12 @@ function parseManifest(bundleDir) {
if (typeof asset.contentType !== 'string' || asset.contentType.length === 0) {
throw failure(`manifest asset ${asset.path} has no contentType`)
}
if (asset.brotliByteLength !== undefined) {
assertInteger(asset.brotliByteLength, `assets[${asset.path}].brotliByteLength`)
if (asset.brotliByteLength >= asset.byteLength) {
throw failure(`manifest asset ${asset.path} declares a brotli copy no smaller than itself`)
}
}
}
if (!manifest.assets.some((asset) => asset.path === manifest.entrypoint)) {
throw failure(`manifest entrypoint ${manifest.entrypoint} is not one of its assets`)
@@ -132,13 +139,33 @@ function listBundleFiles(directory, prefix = '') {
return found
}
// Mirrors mobileWebBundleBrotliPath in src/shared/mobile-web-bundle/manifest-contract.ts.
function brotliPath(asset) {
return `${asset.path}.br`
}
function brotliCopies(manifest) {
return manifest.assets.filter((asset) => asset.brotliByteLength !== undefined)
}
function statSize(bundleDir, path) {
try {
return statSync(join(bundleDir, path)).size
} catch (error) {
throw failure(
`manifest lists ${path}, which is missing from ${bundleDir} (${error.code ?? error.message}). ${REMEDY}`
)
}
}
// Reject unlisted on-disk assets: content-addressed stale files survive interrupted builds and would ship unreachable/unverified in asar.
function assertNoUnlistedFiles(bundleDir, manifest) {
// A dark build's marker is accounted for here; packaging refuses it through assertNotDarkBuild.
const listed = new Set([
'manifest.json',
...darkBuildMarkerFileNames(),
...manifest.assets.map((asset) => asset.path)
...manifest.assets.map((asset) => asset.path),
...brotliCopies(manifest).map((asset) => brotliPath(asset))
])
const strays = listBundleFiles(bundleDir).filter((path) => !listed.has(path))
if (strays.length > 0) {
@@ -155,14 +182,7 @@ function assertMobileWebBundleBuilt(bundleDir = MOBILE_WEB_BUNDLE_DIR) {
assertNoUnlistedFiles(bundleDir, manifest)
for (const asset of manifest.assets) {
const assetPath = join(bundleDir, asset.path)
let size
try {
size = statSync(assetPath).size
} catch (error) {
throw failure(
`manifest lists ${asset.path}, which is missing from ${bundleDir} (${error.code ?? error.message}). ${REMEDY}`
)
}
const size = statSize(bundleDir, asset.path)
if (size !== asset.byteLength) {
throw failure(
`${asset.path} is ${String(size)} bytes on disk, manifest says ${String(asset.byteLength)}. ${REMEDY}`
@@ -175,6 +195,20 @@ function assertMobileWebBundleBuilt(bundleDir = MOBILE_WEB_BUNDLE_DIR) {
)
}
}
// Phones verify only the inflated bytes, so a copy that inflates to anything else fails every download.
for (const asset of brotliCopies(manifest)) {
const path = brotliPath(asset)
const size = statSize(bundleDir, path)
if (size !== asset.brotliByteLength) {
throw failure(
`${path} is ${String(size)} bytes on disk, manifest says ${String(asset.brotliByteLength)}. ${REMEDY}`
)
}
const inflated = brotliDecompressSync(readFileSync(join(bundleDir, path)))
if (createHash('sha256').update(inflated).digest('hex') !== asset.sha256) {
throw failure(`${path} does not inflate to ${asset.path}. ${REMEDY}`)
}
}
console.log(
`[verify-packaged-mobile-web-bundle] OK — buildId ${manifest.buildId}, ` +
`${String(manifest.assets.length)} asset(s), ${String(manifest.totalBytes)} bytes`
@@ -2,6 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { brotliCompressSync } from 'node:zlib'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { writeMobileWebBundleFixtureTree } from '../../build/mobile-web-app/mobile-web-bundle-fixture-tree.mjs'
@@ -10,11 +11,11 @@ const { assertMobileWebBundleBuilt } = require('./verify-packaged-mobile-web-bun
const electronBuilderConfig = require('../../../electron-builder.config.cjs')
const { darkBuildMarkers } = require('../../../dark-build-switches.cjs')
async function withBundle(run) {
async function withBundle(run, { brotli = false } = {}) {
const scratch = await mkdtemp(join(tmpdir(), 'orca-mobile-web-guard-'))
const bundleDir = join(scratch, 'mobile-web')
try {
const { manifest } = await writeMobileWebBundleFixtureTree({ outDir: bundleDir })
const { manifest } = await writeMobileWebBundleFixtureTree({ outDir: bundleDir, brotli })
await run({ bundleDir, manifest })
} finally {
await rm(scratch, { recursive: true, force: true })
@@ -65,6 +66,25 @@ describe('assertMobileWebBundleBuilt', () => {
})
})
it('accepts the brotli copies the manifest lists, and fails one that inflates to other bytes', async () => {
await withBundle(
async ({ bundleDir, manifest }) => {
const asset = manifest.assets.find((entry) => entry.brotliByteLength !== undefined)
expect(() => assertMobileWebBundleBuilt(bundleDir)).not.toThrow()
const forged = brotliCompressSync(Buffer.from('not the asset'))
await writeFile(join(bundleDir, `${asset.path}.br`), forged)
await rewriteManifest(bundleDir, (rewritten) => {
rewritten.assets.find((entry) => entry.path === asset.path).brotliByteLength =
forged.byteLength
})
expect(() => assertMobileWebBundleBuilt(bundleDir)).toThrow(
`${asset.path}.br does not inflate to ${asset.path}`
)
},
{ brotli: true }
)
})
it('refuses an asset path that escapes the bundle directory', async () => {
await withBundle(async ({ bundleDir }) => {
await rewriteManifest(bundleDir, (manifest) => {
+1 -1
View File
@@ -44,7 +44,7 @@ Tokens pair a **surface** with a **foreground** that meets contrast on it; alway
- Body letter-spacing is set globally on `body`; don't override per component.
- Use Tailwind's scale. Common: 14px body/default buttons, 13px sidebar items and dense rows, 12px sub-text and paths, 11px uppercase meta/captions.
- Use `text-2xs` (11px) and `text-3xs` (10px), not `text-[11px]` / `text-[10px]`.
- Category labels: 11px, `font-semibold`, `uppercase`, `tracking-wider` (0.05em).
- Category labels: 11px, `font-semibold`, `uppercase`, `tracking-wider` (0.05em). Settings content uses sentence case without tracking: 14px row labels, `text-settings-detail` (12.5px) help, and `text-settings-heading` (15px) semibold section headings. Settings form rows use about 9px vertical padding (44px minimum), selects are 28px, and the centered content column is at most 720px with at least 32px side gutters. These density rules are scoped to `.settings-view-shell`; shared primitives retain their defaults elsewhere.
- Native chat has its own lint-enforced scale and colours: see [native-chat.md](./styleguide/native-chat.md).
## Radius and elevation
Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 KiB

After

Width:  |  Height:  |  Size: 473 KiB

@@ -15,6 +15,8 @@ android {
}
dependencies {
// Android ships no brotli decoder; Google's pure-Java one, as okhttp-brotli uses.
implementation 'org.brotli:dec:0.1.2'
testImplementation 'junit:junit:4.13.2'
// The android.jar used by JVM unit tests stubs org.json; the shared vectors are JSON.
testImplementation 'org.json:json:20240303'
@@ -0,0 +1,31 @@
package expo.modules.orcagziputf8codec
import java.io.ByteArrayInputStream
import java.io.IOException
import org.brotli.dec.BrotliInputStream
class BoundedBrotliException(message: String) : Exception(message)
/** Inflate one brotli stream into at most outputLimit bytes; callers pass one byte beyond the length they
* accept and check the result's length and hash, so truncated or overlong input fails there. */
fun brotliDecompressBounded(input: ByteArray, outputLimit: Int): ByteArray {
if (outputLimit <= 0 || input.isEmpty()) {
throw BoundedBrotliException("nothing to inflate")
}
val output = ByteArray(outputLimit)
var produced = 0
try {
BrotliInputStream(ByteArrayInputStream(input)).use { stream ->
while (produced < outputLimit) {
val count = stream.read(output, produced, outputLimit - produced)
if (count < 0) {
break
}
produced += count
}
}
} catch (error: IOException) {
throw BoundedBrotliException(error.message ?: "invalid brotli data")
}
return if (produced == outputLimit) output else output.copyOf(produced)
}
@@ -15,5 +15,10 @@ class OrcaGzipUtf8CodecModule : Module() {
Function("decodeUtf8") { input: ByteArray ->
decodeStrictUtf8(input)
}
// Async: a whole bundle asset can take tens of ms, too long to hold the JS thread.
AsyncFunction("brotliDecompress") { input: ByteArray, outputLimit: Int ->
brotliDecompressBounded(input, outputLimit)
}
}
}
@@ -0,0 +1,28 @@
import Compression
import Foundation
struct BoundedBrotliError: Error, CustomStringConvertible {
let description: String
}
/// Inflate one brotli stream into at most outputLimit bytes; callers pass one byte beyond the length they
/// accept and check the result's length and hash. Compression returns nothing for a stream that is invalid,
/// truncated or longer than the buffer, so all three throw here.
func brotliDecompressBounded(_ input: Data, outputLimit: Int) throws -> Data {
guard outputLimit > 0, !input.isEmpty else {
throw BoundedBrotliError(description: "nothing to inflate")
}
var output = Data(count: outputLimit)
let produced = input.withUnsafeBytes { (inBytes: UnsafeRawBufferPointer) -> Int in
output.withUnsafeMutableBytes { (outBytes: UnsafeMutableRawBufferPointer) -> Int in
compression_decode_buffer(
outBytes.bindMemory(to: UInt8.self).baseAddress!, outputLimit,
inBytes.bindMemory(to: UInt8.self).baseAddress!, inBytes.count,
nil, COMPRESSION_BROTLI)
}
}
guard produced > 0 else {
throw BoundedBrotliError(description: "not a whole brotli stream within the output limit")
}
return produced == outputLimit ? output : output.prefix(produced)
}
@@ -1,7 +1,7 @@
Pod::Spec.new do |s|
s.name = 'OrcaGzipUtf8Codec'
s.version = '0.0.1'
s.summary = 'Bounded gunzip and strict UTF-8 decode'
s.summary = 'Bounded gunzip and brotli inflate, and strict UTF-8 decode'
s.description = s.summary
s.license = { :type => 'MIT' }
s.author = 'Orca'
@@ -11,6 +11,6 @@ Pod::Spec.new do |s|
s.swift_version = '5.9'
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.libraries = 'z'
s.libraries = 'z', 'compression'
s.source_files = '**/*.swift'
end
@@ -12,5 +12,10 @@ public class OrcaGzipUtf8CodecModule: Module {
Function("decodeUtf8") { (input: Data) -> String? in
decodeStrictUtf8(input)
}
// Async: a whole bundle asset can take tens of ms, too long to hold the JS thread.
AsyncFunction("brotliDecompress") { (input: Data, outputLimit: Int) throws -> Data in
try brotliDecompressBounded(input, outputLimit: outputLimit)
}
}
}
@@ -5,6 +5,8 @@ export type OrcaGzipUtf8CodecModule = {
gunzip(input: Uint8Array, outputLimit: number): Uint8Array
/** Well-formed UTF-8 with no leading BOM, decoded; null otherwise. */
decodeUtf8(input: Uint8Array): string | null
/** Inflate one brotli stream into at most outputLimit bytes, off the JS thread; throws on bad input. */
brotliDecompress(input: Uint8Array, outputLimit: number): Promise<Uint8Array<ArrayBuffer>>
}
/** Null in a binary built before the module existed. */
+19 -52
View File
@@ -1,22 +1,18 @@
import { memo } from 'react'
import { lazy, Suspense } from 'react'
import { View, StyleSheet } from 'react-native'
import { MobileSourceControlRoutePanel } from '../source-control/MobileSourceControlRoutePanel'
import { MobileFileExplorerPanel } from '../files/MobileFileExplorerPanel'
import { mobilePrSidebarStyles } from '../components/pr-sidebar/mobile-pr-sidebar-styles'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { useMobileDockResize } from './use-mobile-dock-resize'
import type { ActivePanel } from './session-panel-host'
import type { SessionDockPanelContentProps } from './SessionDockPanelContent'
type Props = {
activePanel: Exclude<ActivePanel, null>
hostId: string
worktreeId: string
name: string
availableWidth: number
onRequestClose: () => void
}
type Props = SessionDockPanelContentProps & { availableWidth: number }
type DockPanelContentProps = Omit<Props, 'availableWidth'>
// Panels load with the first dock open so phone sessions, which never dock, skip Source Control and Files code.
const SessionDockPanelContent = lazy(() =>
import('./SessionDockPanelContent').then((module) => ({
default: module.SessionDockPanelContent
}))
)
// Keep drag width state in this subtree; terminal refits follow frame onLayout and need no width prop.
export function SessionDockColumn({
@@ -34,49 +30,20 @@ export function SessionDockColumn({
{/* Dedicated drag handle over the dock's left border — a leaf overlay so the
inner ScrollView can't intercept the gesture on Android. */}
<View style={styles.resizeHandle} {...panHandlers} />
<DockPanelContent
activePanel={activePanel}
hostId={hostId}
worktreeId={worktreeId}
name={name}
onRequestClose={onRequestClose}
/>
{/* The column frame paints at once; its panel fills in from local disk with no spinner. */}
<Suspense fallback={null}>
<SessionDockPanelContent
activePanel={activePanel}
hostId={hostId}
worktreeId={worktreeId}
name={name}
onRequestClose={onRequestClose}
/>
</Suspense>
</View>
)
}
// Width-independent panel props let memo skip content rerenders during resize.
const DockPanelContent = memo(function DockPanelContent({
activePanel,
hostId,
worktreeId,
name,
onRequestClose
}: DockPanelContentProps) {
// Reuse the source-control hub so dock icon switches retain commit draft, visited tabs and scroll.
if (activePanel === 'sourceControl' || activePanel === 'pr') {
return (
<MobileSourceControlRoutePanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
initialTab={activePanel === 'pr' ? 'pr' : 'changes'}
onRequestClose={onRequestClose}
/>
)
}
return (
<MobileFileExplorerPanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
onRequestClose={onRequestClose}
/>
)
})
const RESIZE_EDGE_WIDTH = 24
const styles = StyleSheet.create({
@@ -0,0 +1,44 @@
import { memo } from 'react'
import { MobileSourceControlRoutePanel } from '../source-control/MobileSourceControlRoutePanel'
import { MobileFileExplorerPanel } from '../files/MobileFileExplorerPanel'
import type { ActivePanel } from './session-panel-host'
export type SessionDockPanelContentProps = {
activePanel: Exclude<ActivePanel, null>
hostId: string
worktreeId: string
name: string
onRequestClose: () => void
}
// Width-independent panel props let memo skip content rerenders during resize.
export const SessionDockPanelContent = memo(function SessionDockPanelContent({
activePanel,
hostId,
worktreeId,
name,
onRequestClose
}: SessionDockPanelContentProps) {
// Reuse the source-control hub so dock icon switches retain commit draft, visited tabs and scroll.
if (activePanel === 'sourceControl' || activePanel === 'pr') {
return (
<MobileSourceControlRoutePanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
initialTab={activePanel === 'pr' ? 'pr' : 'changes'}
onRequestClose={onRequestClose}
/>
)
}
return (
<MobileFileExplorerPanel
hostId={hostId}
worktreeId={worktreeId}
name={name}
embedded
onRequestClose={onRequestClose}
/>
)
})
+38 -13
View File
@@ -6,7 +6,7 @@ import type { TerminalWebViewHandle, TerminalWebViewProps } from './terminal-web
import { TerminalWebViewEngineErrorOverlay } from './terminal-webview-engine-error-state'
import { TERMINAL_WEBVIEW_FRAME_STYLES } from './terminal-webview-frame-styles'
import type { TerminalWebViewCommand } from './terminal-webview-messages'
import { mountTerminalWebDocument, type TerminalWebDocument } from './terminal-web-document-mount'
import type { TerminalWebDocument } from './terminal-web-document-mount'
import { useTerminalWebViewController } from './use-terminal-webview-controller'
type Props = TerminalWebViewProps
@@ -68,27 +68,52 @@ export const TerminalWebView = forwardRef<TerminalWebViewHandle, Props>(
if (!(host instanceof HTMLElement)) {
return
}
let live
try {
live = mountTerminalWebDocument(host, (message) => receiveRef.current?.(message), atMount)
} catch (error) {
let live: TerminalWebDocument | null = null
let disposed = false
const reportStartupFailure = (error: unknown) => {
// Startup failure has no handle or later error notify; report its cause now instead of waiting for readiness timeout.
receiveRef.current?.({
type: 'error',
fatal: true,
message: describeTerminalDocumentStartupError(error)
})
return
}
documentRef.current = live
// Replay the pre-handle ready flush; theme/scale also ride init today, but future commands may not.
for (const command of beforeMountRef.current) {
live.send(command)
}
beforeMountRef.current = []
// Load xterm with the first terminal so chat-only sessions never parse it; posts queue in beforeMountRef meanwhile.
void import('./terminal-web-document-mount').then(
({ mountTerminalWebDocument }) => {
if (disposed) {
return
}
try {
live = mountTerminalWebDocument(
host,
(message) => receiveRef.current?.(message),
atMount
)
documentRef.current = live
// Replay the pre-handle ready flush; theme/scale also ride init today, but future commands may not.
for (const command of beforeMountRef.current) {
live.send(command)
}
beforeMountRef.current = []
} catch (error) {
// A throw here would escape the promise unseen; ready already stopped the watchdog, so show the overlay.
documentRef.current = null
live?.dispose()
live = null
reportStartupFailure(error)
}
},
(error: unknown) => {
if (!disposed) {
reportStartupFailure(error)
}
}
)
return () => {
disposed = true
documentRef.current = null
live.dispose()
live?.dispose()
}
// Mount once per generation; callback-driven controller changes must not discard terminal scrollback.
}, [atMount, generation])
@@ -1,4 +1,4 @@
import { gunzipSync } from 'node:zlib'
import { brotliDecompressSync, gunzipSync } from 'node:zlib'
import sodium from 'react-native-libsodium'
import { beforeAll, describe, expect, it, vi } from 'vitest'
@@ -38,6 +38,8 @@ function libsodiumBindings(): PairedE2EENativeBindings {
},
codec: {
gunzip: (input, outputLimit) => new Uint8Array(gunzipSync(input)).slice(0, outputLimit),
brotliDecompress: async (input, outputLimit) =>
new Uint8Array(brotliDecompressSync(input)).slice(0, outputLimit),
decodeUtf8: (input) => {
if (input[0] === 0xef && input[1] === 0xbb && input[2] === 0xbf) {
return null
@@ -1,4 +1,4 @@
// Move frame seal/decode and bundle gunzip off Hermes’s JS thread when native bindings are available.
// Move frame seal/decode and bundle gunzip/brotli off Hermes’s JS thread when native bindings are available.
export type PairedE2EENativeCodec = {
/** Canonical padded base64 only; null for anything else, including what `atob` forgives. */
decodeBase64(value: string): Uint8Array | null
@@ -10,6 +10,8 @@ export type PairedE2EENativeCodec = {
sealSecretbox(message: Uint8Array, nonce: Uint8Array, key: Uint8Array): Uint8Array
/** Throws on a body that is not one well-formed gzip member. See orca-gzip-utf8-codec. */
gunzip(input: Uint8Array, outputLimit: number): Uint8Array
/** Off the JS thread; Hermes has no brotli, so there is no JS fallback. */
brotliDecompress(input: Uint8Array, outputLimit: number): Promise<Uint8Array<ArrayBuffer>>
/** Null where only TextDecoder's replacement or BOM rules give the answer, or native failed. */
decodeUtf8(input: Uint8Array): string | null
}
@@ -25,6 +27,7 @@ export type PairedE2EENativeBindings = {
codec: {
gunzip(input: Uint8Array, outputLimit: number): Uint8Array
decodeUtf8(input: Uint8Array): string | null
brotliDecompress(input: Uint8Array, outputLimit: number): Promise<Uint8Array<ArrayBuffer>>
}
sodium: LibsodiumBindings
}
@@ -96,6 +99,7 @@ function detectPairedE2EENativeCodec(): PairedE2EENativeCodec | null {
sodium.secretboxSeal(wholeBuffer(message), wholeBuffer(nonce), wholeBuffer(key))
),
gunzip: (input, outputLimit) => module.gunzip(input, outputLimit),
brotliDecompress: (input, outputLimit) => module.brotliDecompress(input, outputLimit),
decodeUtf8: (input) => {
// Why: the frame is already open and the counter advanced, so a throw here must not drop it.
try {
@@ -0,0 +1,116 @@
import { sha256 } from '@noble/hashes/sha256'
import { brotliCompressSync, brotliDecompressSync } from 'node:zlib'
import { describe, expect, it, vi } from 'vitest'
import { computeMobileWebBundleId } from '../../../../src/shared/mobile-web-bundle/manifest-contract'
import { fetchMobileWebBundle, type MobileWebBundleFetchProgress } from './mobile-web-bundle-fetch'
import type { RpcClient } from '../rpc/rpc-client-contract'
import type { RpcResponse } from '../rpc/rpc-wire-types'
vi.mock('expo-crypto', async () => {
const { sha256: hash } = await import('@noble/hashes/sha256')
return {
CryptoDigestAlgorithm: { SHA256: 'SHA-256' },
digest: async (_algorithm: string, data: Uint8Array) => hash(data).buffer
}
})
// The native codec as a phone binary has it; node's brotli stands in for the platform decoder.
vi.mock('../encryption/paired-e2ee-native-codec', () => ({
pairedE2EENativeCodec: () => ({
decodeBase64: (value: string) => new Uint8Array(Buffer.from(value, 'base64')),
brotliDecompress: async (input: Uint8Array, outputLimit: number) =>
new Uint8Array(brotliDecompressSync(input)).slice(0, outputLimit)
})
}))
const toHex = (bytes: Uint8Array): string =>
Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')
// Small enough that the 46-byte brotli copy spans three windows.
const RANGE_BYTES = 16
const SCRIPT = 'export const greeting = "hello";\n'.repeat(40)
const MARK = 'a short mark'
function brotliHost() {
const files = new Map([
['assets/script.js', new TextEncoder().encode(SCRIPT)],
['index.html', new TextEncoder().encode(MARK)]
])
const copy = new Uint8Array(brotliCompressSync(files.get('assets/script.js')!))
const assets = [...files].map(([path, content]) => ({
path,
sha256: toHex(sha256(content)),
byteLength: content.byteLength,
contentType: 'text/plain',
...(path === 'assets/script.js' ? { brotliByteLength: copy.byteLength } : {})
}))
const buildId = computeMobileWebBundleId(assets)
const manifest = {
schemaVersion: 1,
buildId,
desktopVersion: '1.4.300',
minCompatibleRuntimeProtocolVersion: 2,
runtimeProtocolVersion: 2,
entrypoint: 'index.html',
totalBytes: assets.reduce((total, entry) => total + entry.byteLength, 0),
assets
}
const methods: string[] = []
const answer = (method: string, params: Record<string, unknown>): unknown => {
if (method === 'mobileWeb.bundle.manifest') {
return { manifest, chunkBytes: RANGE_BYTES, rangeBytes: RANGE_BYTES }
}
const path = String(params.path)
const offset = Number(params.offset)
const content = files.get(path)!
const stream = method === 'mobileWeb.bundle.brotliRange' ? copy : content
const slice = stream.subarray(offset, offset + RANGE_BYTES)
return {
buildId,
path,
offset,
assetByteLength: content.byteLength,
sha256: toHex(sha256(content)),
...(method === 'mobileWeb.bundle.range' ? { encoding: 'identity' } : {}),
dataBase64: Buffer.from(slice).toString('base64'),
eof: offset + slice.byteLength >= stream.byteLength
}
}
const client: RpcClient = {
sendRequest: vi.fn(async (method: string, params?: unknown): Promise<RpcResponse> => {
methods.push(method)
const fields: Record<string, unknown> = Object(params)
return { id: 'rpc-1', ok: true, result: answer(method, fields), _meta: { runtimeId: 'r' } }
}),
subscribe: vi.fn(() => () => {}),
updateTerminalSubscriptionViewport: vi.fn(),
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => 1,
onStateChange: () => () => {},
notifyForeground: vi.fn(),
close: vi.fn()
}
return { client, methods }
}
describe('fetchMobileWebBundle from a host that ships brotli copies', () => {
it('reads the copy where the manifest lists one, inflates it, and reports progress in asset bytes', async () => {
const host = brotliHost()
const progress: MobileWebBundleFetchProgress[] = []
const fetched = await fetchMobileWebBundle({
client: host.client,
onProgress: (update) => progress.push(update)
})
expect(new TextDecoder().decode(fetched.assets.get('assets/script.js'))).toBe(SCRIPT)
expect(new TextDecoder().decode(fetched.assets.get('index.html'))).toBe(MARK)
expect(host.methods.filter((method) => method === 'mobileWeb.bundle.brotliRange')).toHaveLength(
3
)
expect(host.methods.filter((method) => method === 'mobileWeb.bundle.range')).toHaveLength(1)
expect(progress.at(-1)).toMatchObject({ receivedBytes: 1332, totalBytes: 1332 })
})
})
@@ -10,11 +10,15 @@ import type { RpcClient } from '../rpc/rpc-client-contract'
import { MobileWebBundleFetchError } from './mobile-web-bundle-fetch-refusal'
import { markRpcDeliveryUnknown } from '../rpc/rpc-delivery-ambiguity'
import { runRpcOperation } from '../rpc/rpc-operation'
import { mobileWebBundleWindowReader } from './mobile-web-bundle-window-reader'
import {
mobileWebBundleWindowReader,
type MobileWebBundleWindowReader
} from './mobile-web-bundle-window-reader'
import {
assertWindowDescribesAsset,
assertWindowFillsItsSlot,
windowSlotBytes
windowSlotBytes,
type MobileWebBundleWindowStream
} from './mobile-web-bundle-window-checks'
// The host admits four window reads per connection; one reader per asset would serialize large scripts.
@@ -56,6 +60,7 @@ export type MobileWebBundleFetchResult = {
type AssetReassembly = {
readonly entry: MobileWebBundleAssetRead
readonly stream: MobileWebBundleWindowStream
readonly whole: Uint8Array<ArrayBuffer>
outstandingWindows: number
}
@@ -154,9 +159,9 @@ export async function fetchMobileWebBundle(args: {
return
}
assertWindowDescribesAsset(reply.header, asset.entry, manifest.buildId, offset)
const bytes = reply.bytes(windowSlotBytes(asset.entry, offset, reader.windowBytes))
const bytes = reply.bytes(windowSlotBytes(asset.stream, offset, reader.windowBytes))
assertWindowFillsItsSlot(
asset.entry,
asset.stream,
offset,
bytes.byteLength,
reply.header.eof,
@@ -165,7 +170,7 @@ export async function fetchMobileWebBundle(args: {
asset.whole.set(bytes, offset)
asset.outstandingWindows -= 1
if (asset.outstandingWindows === 0) {
const verified = await verifyReassembledAsset(asset)
const verified = await verifyReassembledAsset(asset, reader)
throwIfCallerAborted(args.signal)
// A sibling failed while this hashed; the fetch already rejected with that failure.
if (stopped.signal.aborted) {
@@ -175,12 +180,12 @@ export async function fetchMobileWebBundle(args: {
downloadedAssets += 1
}
// Per window, not per asset: the largest asset goes first, so asset completions bunch at the end.
receivedBytes += bytes.byteLength
receivedBytes += assetBytesCredited(asset, offset, bytes.byteLength)
reportProgress()
}
const readWindows = async (entries: readonly MobileWebBundleAssetRead[]): Promise<void> => {
const queue = planWindowReads(entries, reader.windowBytes)
const queue = planWindowReads(entries, reader)
if (queue.length === 0) {
return
}
@@ -270,30 +275,61 @@ export async function fetchMobileWebBundle(args: {
// Plan all grid offsets largest-asset first so its tail cannot serialize the end; still validate eof replies.
function planWindowReads(
entries: readonly MobileWebBundleAssetRead[],
windowBytes: number
reader: MobileWebBundleWindowReader
): WindowRead[] {
const largestFirst = [...entries].sort((left, right) => right.byteLength - left.byteLength)
return largestFirst.flatMap((entry) => {
const count = Math.max(1, Math.ceil(entry.byteLength / windowBytes))
const { windowBytes } = reader
const streams = entries.map((entry) => ({
entry,
stream: { path: entry.path, byteLength: reader.streamLength(entry) }
}))
const largestFirst = streams.sort(
(left, right) => right.stream.byteLength - left.stream.byteLength
)
return largestFirst.flatMap(({ entry, stream }) => {
const count = Math.max(1, Math.ceil(stream.byteLength / windowBytes))
const asset: AssetReassembly = {
entry,
whole: new Uint8Array(entry.byteLength),
stream,
whole: new Uint8Array(stream.byteLength),
outstandingWindows: count
}
return Array.from({ length: count }, (_, index) => ({ asset, offset: index * windowBytes }))
})
}
async function verifyReassembledAsset(asset: AssetReassembly): Promise<Uint8Array> {
// Progress stays in asset bytes, the unit of the session's total: a window of a brotli copy counts for its
// share of the asset, and an asset's windows add up to exactly its byteLength.
function assetBytesCredited(asset: AssetReassembly, offset: number, byteLength: number): number {
const streamBytes = asset.stream.byteLength
if (streamBytes === asset.entry.byteLength) {
return byteLength
}
const at = (position: number): number =>
Math.floor((asset.entry.byteLength * position) / streamBytes)
return at(offset + byteLength) - at(offset)
}
async function verifyReassembledAsset(
asset: AssetReassembly,
reader: MobileWebBundleWindowReader
): Promise<Uint8Array> {
const whole = await reader.inflate(asset.entry, asset.whole)
const { path, byteLength } = asset.entry
if (whole.byteLength !== byteLength) {
throw new MobileWebBundleFetchError(
whole.byteLength > byteLength ? 'asset-overlong' : 'asset-short',
`bundle asset ${path} inflated to ${whole.byteLength} of ${byteLength} declared bytes`
)
}
// Native: hashing in JS held the JS thread for seconds, and React's progress renders waited on it.
const hashed = toHex(new Uint8Array(await digest(CryptoDigestAlgorithm.SHA256, asset.whole)))
const hashed = toHex(new Uint8Array(await digest(CryptoDigestAlgorithm.SHA256, whole)))
if (hashed !== asset.entry.sha256) {
throw new MobileWebBundleFetchError(
'asset-checksum-mismatch',
`bundle asset ${asset.entry.path} hashed ${hashed}, not ${asset.entry.sha256}`
)
}
return asset.whole
return whole
}
/** Only the caller's abort surfaces as `fetch-stopped`; an internal stop rejects with the failure
@@ -1,11 +1,13 @@
import {
MobileWebBundleErrorCodeSchema,
MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD,
MOBILE_WEB_BUNDLE_CHUNK_METHOD,
MOBILE_WEB_BUNDLE_MANIFEST_METHOD,
MOBILE_WEB_BUNDLE_RANGE_METHOD,
type MobileWebBundleErrorCode
} from '../../../../src/shared/mobile-web-bundle/bundle-rpc-contract'
import {
MobileWebBundleBrotliRangeReplySchema,
MobileWebBundleChunkReplySchema,
MobileWebBundleManifestReplySchema,
MobileWebBundleRangeReplySchema
@@ -43,6 +45,15 @@ export const mobileWebBundleRangeRead = defineRpcOperation({
read: rpcResultVariant('mobile-web-bundle-range', MobileWebBundleRangeReplySchema)
})
// Only for assets whose manifest entry names a brotli copy, so only hosts that ship one are asked.
export const mobileWebBundleBrotliRangeRead = defineRpcOperation({
name: 'mobileWeb.bundle-brotli-range',
method: MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD,
acceptance: 'require-result-or-throw',
barrier: 'on-settle',
read: rpcResultVariant('mobile-web-bundle-brotli-range', MobileWebBundleBrotliRangeReplySchema)
})
/** A code is a bare snake_case token, so only the two positions one can occupy are read. */
const LEADING_CODE_TOKEN = /^[a-z][a-z0-9_]*/
@@ -38,7 +38,15 @@ const assetSchema = z.looseObject({
path: MobileWebBundleAssetPathSchema,
sha256: z.string().regex(SHA256_PATTERN),
byteLength: z.number().int().nonnegative().max(MOBILE_WEB_BUNDLE_MAX_ASSET_BYTES),
contentType: z.string().min(1)
contentType: z.string().min(1),
// An unreadable length means no brotli copy, never a refused bundle; the reader also requires it under byteLength.
brotliByteLength: z
.number()
.int()
.nonnegative()
.max(MOBILE_WEB_BUNDLE_MAX_ASSET_BYTES)
.optional()
.catch(undefined)
})
// Read unknown schema versions as numbers so compatibility can name the required update.
@@ -115,6 +123,12 @@ export const MobileWebBundleRangeReplySchema = z.looseObject({
dataBase64: z.string().max(MOBILE_WEB_BUNDLE_RANGE_MAX_DATA_BASE64_LENGTH)
})
// Windows of the brotli copy are its raw bytes; the header still names the inflated asset.
export const MobileWebBundleBrotliRangeReplySchema = z.looseObject({
...windowHeaderFields,
dataBase64: z.string().max(MOBILE_WEB_BUNDLE_RANGE_MAX_DATA_BASE64_LENGTH)
})
export type MobileWebBundleManifestReply = z.output<typeof MobileWebBundleManifestReplySchema>
export type MobileWebBundleManifestRead = MobileWebBundleManifestReply['manifest']
export type MobileWebBundleAssetRead = MobileWebBundleManifestRead['assets'][number]
@@ -2,8 +2,11 @@ import type { MobileWebBundleAssetRead } from './mobile-web-bundle-reply-schemas
import { MobileWebBundleFetchError } from './mobile-web-bundle-fetch-refusal'
import type { MobileWebBundleWindowHeader } from './mobile-web-bundle-window-reader'
/** The file the windows are cut from: the asset, or its brotli copy. */
export type MobileWebBundleWindowStream = Pick<MobileWebBundleAssetRead, 'path' | 'byteLength'>
export function windowSlotBytes(
entry: MobileWebBundleAssetRead,
entry: MobileWebBundleWindowStream,
offset: number,
windowBytes: number
): number {
@@ -12,7 +15,7 @@ export function windowSlotBytes(
/** Offsets are planned, so a reply is accepted only if it fills exactly its slot of the grid. */
export function assertWindowFillsItsSlot(
entry: MobileWebBundleAssetRead,
entry: MobileWebBundleWindowStream,
offset: number,
byteLength: number,
eof: boolean,
@@ -1,8 +1,17 @@
import { errorMessage } from '../../../../src/shared/error-message'
import { decodeBase64Bytes } from '../encryption/base64-byte-codec'
import { pairedE2EENativeCodec } from '../encryption/paired-e2ee-native-codec'
import { mobileWebBundleChunkRead, mobileWebBundleRangeRead } from './mobile-web-bundle-operations'
import {
mobileWebBundleBrotliRangeRead,
mobileWebBundleChunkRead,
mobileWebBundleRangeRead
} from './mobile-web-bundle-operations'
import { decodeMobileWebBundleRange } from './mobile-web-bundle-range-decode'
import type { MobileWebBundleManifestReply } from './mobile-web-bundle-reply-schemas'
import type {
MobileWebBundleAssetRead,
MobileWebBundleManifestReply
} from './mobile-web-bundle-reply-schemas'
import { MobileWebBundleFetchError } from './mobile-web-bundle-fetch-refusal'
import type { RpcClient } from '../rpc/rpc-client-contract'
import { runRpcOperation } from '../rpc/rpc-operation'
import type { SendRequestOptions } from '../rpc/unvalidated-rpc-request-port'
@@ -24,6 +33,8 @@ export type MobileWebBundleWindowReply = {
export type MobileWebBundleWindowReader = {
readonly windowBytes: number
/** What this reader moves for the asset: its brotli copy where it reads one, otherwise the asset itself. */
readonly streamLength: (asset: MobileWebBundleAssetRead) => number
read(
window: {
buildId: string
@@ -32,31 +43,48 @@ export type MobileWebBundleWindowReader = {
},
options?: SendRequestOptions
): Promise<MobileWebBundleWindowReply>
/** The asset's bytes from its reassembled stream, before the caller checks their hash. */
readonly inflate: (
asset: MobileWebBundleAssetRead,
stream: Uint8Array<ArrayBuffer>
) => Promise<Uint8Array<ArrayBuffer>>
}
// Choose ranges only from the manifest’s grid; older hosts still serve chunks.
export function mobileWebBundleWindowReader(
client: RpcClient,
opened: Pick<MobileWebBundleManifestReply, 'chunkBytes' | 'rangeBytes'>
opened: Pick<MobileWebBundleManifestReply, 'chunkBytes' | 'rangeBytes' | 'manifest'>
): MobileWebBundleWindowReader {
const { rangeBytes } = opened
if (rangeBytes === undefined) {
return {
windowBytes: opened.chunkBytes,
read: async (window, options) => {
const { dataBase64, ...header } = await runRpcOperation(
client,
mobileWebBundleChunkRead,
window,
options
)
return { header, bytes: () => decodeBase64(dataBase64) }
}
streamLength: (asset) => asset.byteLength,
read: async (window, options) =>
rawWindowReply(await runRpcOperation(client, mobileWebBundleChunkRead, window, options)),
inflate: async (_asset, stream) => stream
}
}
const native = pairedE2EENativeCodec()
// Hermes has no brotli, so without the native codec every asset stays on gzip ranges.
const brotliLengths = new Map(
native === null
? []
: opened.manifest.assets.flatMap((asset) =>
asset.brotliByteLength !== undefined && asset.brotliByteLength < asset.byteLength
? [[asset.path, asset.brotliByteLength] as const]
: []
)
)
return {
windowBytes: rangeBytes,
streamLength: (asset) => brotliLengths.get(asset.path) ?? asset.byteLength,
read: async (window, options) => {
if (brotliLengths.has(window.path)) {
return rawWindowReply(
await runRpcOperation(client, mobileWebBundleBrotliRangeRead, window, options)
)
}
const { dataBase64, encoding, ...header } = await runRpcOperation(
client,
mobileWebBundleRangeRead,
@@ -72,7 +100,35 @@ export function mobileWebBundleWindowReader(
expected
)
}
}
},
inflate: async (asset, stream) =>
native === null || !brotliLengths.has(asset.path)
? stream
: inflateBrotli(native.brotliDecompress, asset, stream)
}
}
// Chunks and brotli windows carry their bytes as they are.
function rawWindowReply({
dataBase64,
...header
}: MobileWebBundleWindowHeader & { readonly dataBase64: string }): MobileWebBundleWindowReply {
return { header, bytes: () => decodeBase64(dataBase64) }
}
// One byte past the asset bounds a bomb; the caller rejects any length but the asset's.
async function inflateBrotli(
brotliDecompress: (input: Uint8Array, outputLimit: number) => Promise<Uint8Array<ArrayBuffer>>,
asset: MobileWebBundleAssetRead,
stream: Uint8Array
): Promise<Uint8Array<ArrayBuffer>> {
try {
return await brotliDecompress(stream, asset.byteLength + 1)
} catch (error) {
throw new MobileWebBundleFetchError(
'range-undecodable',
`bundle asset ${asset.path} is not valid brotli: ${errorMessage(error)}`
)
}
}
@@ -30,6 +30,7 @@ import { claudeStoppedRequestEndWait } from '../claude-request-end-wait'
import {
finishClaudeCloseAfterExit,
drainClaudeObservedExits,
liveClaudeSession,
observeClaudeSessionExit,
settleClaudeUnexpectedExit,
type ClaudeExitLifecycle
@@ -296,15 +297,6 @@ export class ClaudeStructuredSessionAdapter implements StructuredAgentSessionAda
}
private session(sessionId: string): ClaudeSession {
const session = this.sessions.get(sessionId)
if (!session) {
// A child that just exited is named by its own diagnostic, not by its absence.
throw (
this.exits.get(sessionId)?.error ??
this.settledExitErrors.get(sessionId) ??
new Error(`no live claude stream-json session for ${sessionId}`)
)
}
return session
return liveClaudeSession(this.exitLifecycle, sessionId)
}
}
@@ -255,3 +255,19 @@ export function finishClaudeCloseAfterExit(input: {
})
)
}
export function liveClaudeSession(
lifecycle: ClaudeExitLifecycle,
sessionId: string
): ClaudeSession {
const session = lifecycle.sessions.get(sessionId)
if (!session) {
// A child that just exited is named by its own diagnostic, not by its absence.
throw (
lifecycle.exits.get(sessionId)?.error ??
lifecycle.settledExitErrors.get(sessionId) ??
new Error(`no live claude stream-json session for ${sessionId}`)
)
}
return session
}
@@ -57,7 +57,7 @@ export function parseDaemonPidFile(contents: string): ParsedDaemonPid | null {
}
const pid = Number(trimmed)
return Number.isFinite(pid)
return Number.isSafeInteger(pid) && pid > 0
? {
pid,
startedAtMs: null,
@@ -284,7 +284,7 @@ export function collectPinnedDaemonVersions(runtimeDir: string): PinnedDaemonVer
}
}
const parsed = parseDaemonPidFile(contents)
// Empty records can parse as PID 0 during publication; they must veto pruning instead of appearing legacy.
// Records are empty during publication; a torn record must veto pruning instead of appearing legacy.
if (!parsed || !Number.isInteger(parsed.pid) || parsed.pid <= 0) {
return {
status: 'unverifiable',
@@ -367,8 +367,8 @@ describe('killStaleDaemon ownership decisions', () => {
}
})
it('removes a malformed pid record', async () => {
writeFileSync(getDaemonPidPath(dir), '{truncated', { mode: 0o600 })
it.each(['{truncated', ''])('removes a malformed pid record %j', async (record) => {
writeFileSync(getDaemonPidPath(dir), record, { mode: 0o600 })
await killStaleDaemon(dir, socketPath, tokenPath, undefined, {
probeEndpoint: async () => 'missing'
@@ -377,6 +377,20 @@ describe('killStaleDaemon ownership decisions', () => {
expect(existsSync(getDaemonPidPath(dir))).toBe(false)
})
it.each(['connected', 'unknown'] as const)(
'keeps an empty pid record while its endpoint probe is %s',
async (outcome) => {
writeFileSync(getDaemonPidPath(dir), '', { mode: 0o600 })
await expect(
killStaleDaemon(dir, socketPath, tokenPath, undefined, {
probeEndpoint: async () => outcome
})
).resolves.toEqual({ killed: false, liveOwnerSurvived: true })
expect(existsSync(getDaemonPidPath(dir))).toBe(true)
}
)
it.skipIf(process.platform === 'win32')(
"leaves a replacement's pid record after killing the recorded owner",
async () => {
@@ -66,7 +66,7 @@ export async function classifyDaemonGeneration(
return hasErrorCode(error, 'ENOENT') ? 'exited' : byEndpoint()
}
const parsed = parseDaemonPidFile(contents)
// An empty legacy record parses as PID 0, which is not a daemon PID.
// A torn or non-positive record names no daemon PID; only the endpoint can decide.
if (!parsed || !Number.isInteger(parsed.pid) || parsed.pid <= 0) {
return byEndpoint()
}
+9 -4
View File
@@ -64,9 +64,11 @@ export async function killStaleDaemon(
let liveOwnerSurvived = false
// Capture the inspected owner so cleanup cannot remove a later incarnation's record.
let recordedOwner: ParsedDaemonPid | null = null
let malformedRecord = false
try {
const parsedPid = parseDaemonPidFile(readFileSync(pidPath, 'utf8'))
recordedOwner = parsedPid
malformedRecord = parsedPid === null
const identity = parsedPid
? await inspectDaemonProcessIdentity(
parsedPid.pid,
@@ -153,14 +155,17 @@ export async function killStaleDaemon(
// Fence removal to the inspected record so a concurrent replacement keeps its ownership.
if (recordedOwner) {
unlinkOwnedDaemonPidFile(pidPath, recordedOwner.pid, recordedOwner.launchNonce)
} else {
// Reclaim malformed records under a content-checked claim so valid replacements survive.
unlinkDaemonPidFileWhen(pidPath, (content) => parseDaemonPidFile(content) === null)
}
// Only publishers replace dead endpoints; this probe is advisory and never removes another daemon's name.
if ((await probeEndpoint(socketPath)) === 'connected') {
const endpointOutcome = await probeEndpoint(socketPath)
// A replacement cannot publish over a retained malformed record, so an inconclusive probe declines it.
if (endpointOutcome === 'connected' || (malformedRecord && endpointOutcome === 'unknown')) {
return { killed: killedDaemon, liveOwnerSurvived: true }
}
if (malformedRecord && endpointIsProvenDead(endpointOutcome)) {
// A publishing daemon's record is empty until written, so reclaim malformed records only once its endpoint is dead.
unlinkDaemonPidFileWhen(pidPath, (content) => parseDaemonPidFile(content) === null)
}
return { killed: killedDaemon, liveOwnerSurvived }
}
@@ -1,6 +1,7 @@
import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent'
import type { ShellReadyState } from './daemon-rpc-contract'
import type { TerminalSnapshot } from './terminal-snapshot'
import type { DaemonLaunchNote } from './daemon-launch-note-protocol'
import type { AgentSessionClaimedSpawnResult } from '../../../shared/agent-session/agent-session-host-authority'
import type { PtyIncarnationId } from '../../../shared/terminal/pty/lifecycle/pty-incarnation'
@@ -11,6 +12,8 @@ export type DaemonCreateOrAttachResult = {
shellState: ShellReadyState
historySeeded?: boolean
launchAgent?: TuiAgent
/** The launch main armed and has not retired, null for none; older daemons omit it. */
launchNote?: DaemonLaunchNote | null
/** Undefined only when talking to a daemon predating WSL session context. */
wslDistro?: string | null
agentSessionEnsure?: AgentSessionClaimedSpawnResult
@@ -23,15 +26,18 @@ export type DaemonCreateOrAttachResult = {
export function getDaemonSessionResultMetadata(session: {
launchAgent: TuiAgent | null
launchNote: { current: DaemonLaunchNote | null }
historySeeded: boolean | undefined
wslDistro: string | null
}): {
launchAgent?: TuiAgent
launchNote: DaemonLaunchNote | null
historySeeded?: boolean
wslDistro: string | null
} {
return {
...(session.launchAgent ? { launchAgent: session.launchAgent } : {}),
launchNote: session.launchNote.current,
...(session.historySeeded !== undefined ? { historySeeded: session.historySeeded } : {}),
// Null identifies native sessions; only older daemons omit the field.
wslDistro: session.wslDistro
@@ -0,0 +1,62 @@
import type { SleepingAgentLaunchConfig } from '../../../shared/agent-session/lifecycle/agent-session-resume'
/** The Orca launch running in a session, kept by the daemon so it outlives a main restart. */
export type DaemonLaunchNote = { launchToken: string; launchConfig: SleepingAgentLaunchConfig }
/** Main arms the launch it admits and retires it by token, so a stale retire cannot clear a newer launch. */
export type DaemonLaunchNoteChange = { arm: DaemonLaunchNote } | { retire: string }
export type SetLaunchNoteRequest = {
id: string
type: 'setLaunchNote'
payload: { sessionId: string; change: DaemonLaunchNoteChange }
}
const isString = (value: unknown): value is string => typeof value === 'string'
const isRecord = (value: unknown): value is Record<string, unknown> =>
typeof value === 'object' && value !== null
const isStringRecord = (value: unknown): value is Record<string, string> =>
isRecord(value) && Object.values(value).every(isString)
export function parseDaemonLaunchNoteChange(raw: unknown): DaemonLaunchNoteChange | null {
if (!isRecord(raw)) {
return null
}
const { arm, retire } = raw
if (isString(retire)) {
return { retire }
}
const note = parseDaemonLaunchNote(arm)
return note ? { arm: note } : null
}
function parseDaemonLaunchNote(raw: unknown): DaemonLaunchNote | null {
if (!isRecord(raw)) {
return null
}
const { launchToken, launchConfig: config } = raw
if (!isString(launchToken) || launchToken.length === 0 || launchToken.length > 128) {
return null
}
if (!isRecord(config)) {
return null
}
const { agentArgs, agentEnv, agentCommand, ompResumeFilePath } = config
if (
!isString(agentArgs) ||
!isStringRecord(agentEnv) ||
(agentCommand !== undefined && !isString(agentCommand)) ||
(ompResumeFilePath !== undefined && !isString(ompResumeFilePath))
) {
return null
}
return {
launchToken,
launchConfig: {
agentArgs,
agentEnv: { ...agentEnv },
...(agentCommand ? { agentCommand } : {}),
...(ompResumeFilePath ? { ompResumeFilePath } : {})
}
}
}
@@ -25,6 +25,7 @@ import type {
import type * as HistorySeedProtocol from '../history/seed-transfer/terminal-history-seed-transfer-protocol'
import type * as PtyOwnerQueryProtocol from './daemon-pty-owner-query-protocol'
import type { TerminalSnapshot } from './terminal-snapshot'
import type { SetLaunchNoteRequest } from './daemon-launch-note-protocol'
export type SessionState = 'created' | 'spawning' | 'running' | 'exiting' | 'exited'
@@ -270,6 +271,7 @@ export type DaemonRequest =
| TakePendingOutputRequest
| PtyOwnerQueryProtocol.CloseStartupQueryAuthorityRequest
| PtyOwnerQueryProtocol.SetColorQueryReplyColorsRequest
| SetLaunchNoteRequest
export type RpcResponseOk<T = unknown> = {
id: string
@@ -1,3 +1,4 @@
import type { DaemonLaunchNoteChange } from '../../protocol/daemon-launch-note-protocol'
import {
PTY_FOREGROUND_OBSERVATION_PROTOCOL_VERSION,
COMPLETION_PROCESS_INSPECTION_PROTOCOL_VERSION,
@@ -90,6 +91,11 @@ export abstract class DaemonPtyProcessInspection extends DaemonPtyBufferSnapshot
}
}
setLaunchNote(id: string, change: DaemonLaunchNoteChange): void {
// Why fire and forget: an older daemon rejects the request and keeps no note, so restore declines.
void this.client.request('setLaunchNote', { sessionId: id, change }).catch(() => undefined)
}
async confirmShellForeground(id: string): Promise<boolean> {
try {
const result = await this.client.request<{ confirmed: boolean }>('confirmShellForeground', {
@@ -3,10 +3,11 @@ import type { DaemonCreateOrAttachResult as CreateOrAttachResult } from '../../p
export function daemonSpawnResultIdentity(
result: CreateOrAttachResult
): Pick<PtySpawnResult, 'incarnationId' | 'agentSessionEnsure' | 'launchAgent'> {
): Pick<PtySpawnResult, 'incarnationId' | 'agentSessionEnsure' | 'launchAgent' | 'launchNote'> {
return {
...(result.incarnationId ? { incarnationId: result.incarnationId } : {}),
...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}),
...(result.launchAgent ? { launchAgent: result.launchAgent } : {})
...(result.launchAgent ? { launchAgent: result.launchAgent } : {}),
...(result.launchNote !== undefined ? { launchNote: result.launchNote } : {})
}
}
@@ -1,3 +1,4 @@
import { parseDaemonLaunchNoteChange } from '../protocol/daemon-launch-note-protocol'
import { handleDaemonTerminalKill } from './daemon-terminal-kill'
import { handleDaemonFencedTermination } from './daemon-fenced-termination'
import { performance } from 'node:perf_hooks'
@@ -146,6 +147,13 @@ export class DaemonRequestRouter {
return {
confirmed: await this.options.host.confirmShellForeground(request.payload.sessionId)
}
case 'setLaunchNote': {
const change = parseDaemonLaunchNoteChange(request.payload.change)
if (change) {
this.options.host.setLaunchNote(request.payload.sessionId, change)
}
return {}
}
case 'clearScrollback':
this.options.host.clearScrollback(request.payload.sessionId)
return {}
@@ -183,6 +183,7 @@ export class DaemonTerminalAdmission {
shellState: result.shellState,
incarnationId: result.incarnationId,
...(result.launchAgent ? { launchAgent: result.launchAgent } : {}),
...(result.launchNote !== undefined ? { launchNote: result.launchNote } : {}),
wslDistro: result.wslDistro,
...(result.historySeeded !== undefined ? { historySeeded: result.historySeeded } : {}),
...(result.agentSessionEnsure ? { agentSessionEnsure: result.agentSessionEnsure } : {}),
@@ -0,0 +1,37 @@
import {
createOsc133CommandFinishedScanner,
type Osc133CommandFinishedScanner
} from '../../../shared/terminal/output/terminal-osc133-command-finished'
import type {
DaemonLaunchNote,
DaemonLaunchNoteChange
} from '../protocol/daemon-launch-note-protocol'
/** Main's live launch here; retired on command-finished too, since it can finish while main is down. */
export class SessionLaunchNote {
current: DaemonLaunchNote | null = null
private retirement: Osc133CommandFinishedScanner | null = null
scan(data: string): void {
this.retirement?.scan(data)
}
change(change: DaemonLaunchNoteChange): void {
const token = this.current?.launchToken
if ('retire' in change) {
if (change.retire === token) {
this.current = null
this.retirement = null
}
return
}
// Re-arming the same launch keeps the scanner, whose carry may hold a split marker.
const note = change.arm
if (note.launchToken !== token) {
this.current = note
this.retirement = createOsc133CommandFinishedScanner(() =>
this.change({ retire: note.launchToken })
)
}
}
}
@@ -1,8 +1,18 @@
import type { ChildProcessVerdictRead, SubprocessHandle } from './session-subprocess-handle'
import type { TerminalForegroundSample } from '../../../shared/terminal/pty/lifecycle/terminal-foreground-observation'
import { SessionLaunchNote } from './session-launch-note'
export class SessionProcessInspection {
constructor(protected readonly subprocess: SubprocessHandle) {}
/** Main's launch note for this process; Session feeds it the output that can retire it. */
readonly launchNote = new SessionLaunchNote()
readonly processNameIsSpawnFile: boolean
readonly shellIsRootChild: boolean
constructor(protected readonly subprocess: SubprocessHandle) {
this.processNameIsSpawnFile = subprocess.processNameIsSpawnFile === true
this.shellIsRootChild = subprocess.shellIsRootChild === true
}
inspectChildProcesses(fresh?: boolean, ignoreDetached?: boolean): ChildProcessVerdictRead {
return this.subprocess.inspectChildProcesses?.(fresh, ignoreDetached) ?? 'unverifiable'
+1 -4
View File
@@ -28,8 +28,6 @@ export class Session extends SessionProcessInspection {
readonly terminalHandle: string | null
readonly launchAgent: TuiAgent | null
readonly wslDistro: string | null
readonly processNameIsSpawnFile: boolean
readonly shellIsRootChild: boolean
private _state: SessionState = 'running'
private _exitCode: number | null = null
exitCause: TerminalExitCause | undefined
@@ -51,8 +49,6 @@ export class Session extends SessionProcessInspection {
this.terminalHandle = opts.terminalHandle ?? null
this.launchAgent = opts.launchAgent ?? null
this.wslDistro = opts.wslDistro ?? null
this.processNameIsSpawnFile = opts.subprocess.processNameIsSpawnFile === true
this.shellIsRootChild = opts.subprocess.shellIsRootChild === true
this.onSessionExit = opts.onExit
const isAlive = () => !this._disposed && this._state !== 'exited'
const pipeline = createSessionOutputPipeline(opts, isAlive)
@@ -80,6 +76,7 @@ export class Session extends SessionProcessInspection {
try {
this.subprocess.onData((data) => {
if (!this._disposed) {
this.launchNote.scan(data)
this.shellReady.ingestSubprocessData(data)
}
})
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { SessionLaunchNote } from '../session-launch-note'
const NOTE = { launchToken: 'launch-1', launchConfig: { agentArgs: '--verbose', agentEnv: {} } }
const NEXT = { launchToken: 'launch-2', launchConfig: { agentArgs: '', agentEnv: {} } }
// The launch can finish while main is down, so the daemon must retire the note without main.
describe('a daemon session launch note', () => {
it('retires when the launched command finishes, even across a same-launch re-arm', () => {
const note = new SessionLaunchNote()
note.change({ arm: NOTE })
note.scan('agent output\x1b]133;')
note.change({ arm: NOTE })
expect(note.current).toEqual(NOTE)
note.scan('D;143\x07')
expect(note.current).toBeNull()
})
it('ignores a retire for an earlier launch', () => {
const note = new SessionLaunchNote()
note.change({ arm: NOTE })
note.change({ arm: NEXT })
note.change({ retire: 'launch-1' })
expect(note.current).toEqual(NEXT)
})
})
@@ -1,3 +1,4 @@
import type { DaemonLaunchNote } from '../protocol/daemon-launch-note-protocol'
import type { StartupCommandDelivery } from '../../../shared/agent-launch/startup/codex-startup-delivery'
import type { TuiAgent } from '../../../shared/agent-launch/catalog/tui-agent'
import type { ShellReadyState } from '../protocol/daemon-rpc-contract'
@@ -52,6 +53,7 @@ export type CreateOrAttachResult = {
shellState: ShellReadyState
historySeeded?: boolean
launchAgent?: TuiAgent
launchNote?: DaemonLaunchNote | null
wslDistro: string | null
attachToken: symbol
incarnationId: PtyIncarnationId
@@ -1,3 +1,4 @@
import type { DaemonLaunchNoteChange } from '../protocol/daemon-launch-note-protocol'
import { terminalSessionExitCode } from './terminal-host-returned-process'
import { runTerminalCreation, type PendingTerminalCreation } from './terminal-creation-work'
import { beginTerminalHostFencedTermination } from './terminal-host-fenced-termination'
@@ -261,6 +262,10 @@ export class TerminalHost {
)
}
setLaunchNote(sessionId: string, change: DaemonLaunchNoteChange): void {
this.sessions.get(sessionId)?.launchNote.change(change)
}
clearScrollback(sessionId: string): void {
getAliveTerminalHostSession(this.sessions, sessionId).clearScrollback()
}
+4 -1
View File
@@ -12,7 +12,8 @@ export type AgentStatusRuntimeEnrichment = Pick<
| 'getAgentStatusTerminalHandleForPaneKey'
| 'getAgentStatusOrchestrationContextForPaneKey'
| 'getTerminalProcessIncarnation'
>
> &
Partial<Pick<OrcaRuntimeService, 'getLaunchStatementForPaneKey'>>
const MAX_AGENT_STATUS_DROP_TAB_ID_LENGTH = 160
@@ -94,9 +95,11 @@ export function enrichAgentStatusIpcPayload(
}
const terminalHandle = runtime.getAgentStatusTerminalHandleForPaneKey(data.paneKey)
const orchestration = runtime.getAgentStatusOrchestrationContextForPaneKey(data.paneKey)
const launchConfig = runtime.getLaunchStatementForPaneKey?.(data.paneKey, data.agentType)
return {
...data,
...(terminalHandle ? { terminalHandle } : {}),
...(launchConfig !== undefined ? { launchConfig } : {}),
...(orchestration ? { orchestration } : {})
}
}
@@ -7,7 +7,12 @@ import {
} from '../../../wsl/filesystem/wsl-unc-drive-fs-path'
import { PATH_OUTSIDE_ALLOWED_DIRECTORIES } from '../../../../shared/file-access/local-file-access'
import { getAllowedRoots } from './filesystem-allowed-roots'
import { isDescendantOrEqual, isENOENT, normalizeExistingPath } from './filesystem-path-containment'
import {
isDescendantOrEqual,
isDescendantOrEqualExact,
isENOENT,
normalizeExistingPath
} from './filesystem-path-containment'
import {
ensureAuthorizedRootsCache,
isPathAllowedByCanonicalRegisteredRoot,
@@ -16,16 +21,22 @@ import {
export const PATH_ACCESS_DENIED_MESSAGE = `${PATH_OUTSIDE_ALLOWED_DIRECTORIES}. If this blocks a legitimate workflow, please file a GitHub issue.`
/** Lazily share allowed roots across every check in one authorization. */
type AllowedRootsSnapshot = { get: () => Promise<readonly string[]> }
type AllowedRootsSnapshot = {
/** Roots whose own links may be followed; exact roots are excluded. */
getCanonicalizable: () => Promise<readonly string[]>
/** Matched as spelled only: the Unicode-identity fallback would stat through a swapped root link. */
exactRoots: readonly string[]
}
function createAllowedRootsSnapshot(
store: RuntimeStore,
extraRoots: readonly string[] = []
extraRoots: readonly string[] = [],
exactRoots: readonly string[] = []
): AllowedRootsSnapshot {
let roots: Promise<readonly string[]> | undefined
return {
get: () => (roots ??= getAllowedRoots(store).then((found) => [...found, ...extraRoots]))
}
const getCanonicalizable = () =>
(roots ??= getAllowedRoots(store).then((found) => [...found, ...extraRoots]))
return { getCanonicalizable, exactRoots }
}
export async function isPathAllowed(
@@ -34,7 +45,12 @@ export async function isPathAllowed(
allowedRoots?: AllowedRootsSnapshot
): Promise<boolean> {
const resolvedTarget = resolve(targetPath)
return (await (allowedRoots?.get() ?? getAllowedRoots(store))).some((root) =>
if (
(allowedRoots?.exactRoots ?? []).some((root) => isDescendantOrEqualExact(resolvedTarget, root))
) {
return true
}
return (await (allowedRoots?.getCanonicalizable() ?? getAllowedRoots(store))).some((root) =>
isDescendantOrEqual(resolvedTarget, root)
)
}
@@ -44,6 +60,8 @@ export type ResolveAuthorizedPathOptions = {
preserveSymlink?: boolean
/** Roots one caller owns outside the store (desktop: floating workspace; runtime: chat scratch). */
extraRoots?: readonly string[]
/** Roots that must contain the real target as spelled; a root later replaced by a link drops out. */
exactRoots?: readonly string[]
}
export async function resolveAuthorizedPath(
@@ -53,7 +71,7 @@ export async function resolveAuthorizedPath(
): Promise<string> {
const resolvedTarget = resolve(targetPath)
// Reuse store-derived roots while fully checking each candidate.
const allowedRoots = createAllowedRootsSnapshot(store, options.extraRoots)
const allowedRoots = createAllowedRootsSnapshot(store, options.extraRoots, options.exactRoots)
if (!(await isPathAllowedIncludingRegisteredWorktrees(resolvedTarget, store, { allowedRoots }))) {
throw new Error(PATH_ACCESS_DENIED_MESSAGE)
}
@@ -201,7 +219,7 @@ async function isPathAllowedByCanonicalAllowedRoot(
if (!sourcePath) {
return false
}
for (const root of await (allowedRoots?.get() ?? getAllowedRoots(store))) {
for (const root of await (allowedRoots?.getCanonicalizable() ?? getAllowedRoots(store))) {
const resolvedRoot = resolve(root)
if (!isDescendantOrEqual(sourcePath, resolvedRoot)) {
continue
@@ -12,7 +12,8 @@ export function isDescendantOrEqual(resolvedTarget: string, resolvedBase: string
return ancestor !== null && isSameFilesystemObject(ancestor, resolvedBase)
}
function isDescendantOrEqualExact(resolvedTarget: string, resolvedBase: string): boolean {
/** Containment as spelled, with no filesystem I/O. */
export function isDescendantOrEqualExact(resolvedTarget: string, resolvedBase: string): boolean {
if (resolvedTarget === resolvedBase) {
return true
}
@@ -9,7 +9,7 @@ import {
} from './filesystem-auth'
import { isDescendantOrEqual } from './filesystem-path-containment'
import { filePreviewForPath } from '../../../../shared/file-preview/file-preview-kind'
import { getDefaultFloatingWorkspacePath } from '../../floating-workspace-directory'
import { getFloatingWorkspaceFileRoots } from '../../floating-workspace-directory'
import {
isDeviceNamespacePath,
isNetworkSharePath,
@@ -35,7 +35,7 @@ export async function resolveDesktopAuthorizedPath(
): Promise<string> {
return resolveAuthorizedPath(targetPath, store, {
...options,
extraRoots: [getDefaultFloatingWorkspacePath()]
...getFloatingWorkspaceFileRoots(store)
})
}
@@ -6,6 +6,7 @@ import { installFakeAppEnvironment } from '../../../config/scripts/test-runtime/
import type { GlobalSettings } from '../../shared/global-settings-types'
import {
getFloatingWorkspaceFileRoots,
trustFloatingWorkspaceDirectory,
resolveFloatingTerminalCwd,
sanitizeFloatingWorkspaceDirectorySetting
@@ -90,4 +91,24 @@ describe('floating workspace directory', () => {
sanitizeFloatingWorkspaceDirectorySetting(store as never, selectedLink)
).resolves.toBe('')
})
it('never re-points an existing trusted folder swapped for a link when trusting another', async () => {
await mkdir(path.join(tempRoot, 'a'))
const approved = await realpath(path.join(tempRoot, 'a'))
const elsewhere = path.join(tempRoot, 'b')
const other = path.join(tempRoot, 'c')
await mkdir(elsewhere)
await mkdir(other)
const store = createStore({ floatingTerminalCwd: approved })
await trustFloatingWorkspaceDirectory(store, approved)
await rm(approved, { recursive: true })
await symlinkDirectory(elsewhere, approved)
await trustFloatingWorkspaceDirectory(store, other)
const canonicalElsewhere = await realpath(elsewhere)
expect(store.settings.floatingTerminalTrustedCwds).not.toContain(canonicalElsewhere)
store.settings = { ...store.settings, floatingTerminalCwd: canonicalElsewhere }
expect(getFloatingWorkspaceFileRoots(store).exactRoots).toEqual([])
})
})
+57 -15
View File
@@ -1,4 +1,4 @@
import { constants as fsConstants } from 'node:fs'
import { constants as fsConstants, realpathSync } from 'node:fs'
import { access, mkdir, realpath, stat } from 'node:fs/promises'
import path from 'node:path'
import { getAppEnvironment } from '../../shared/app-environment'
@@ -8,6 +8,8 @@ import type { Store } from '../persistence/loading-store/store'
import { resolveFloatingWorkspacePath } from '../persistence/restoring-sessions/floating-workspace-normalization'
type FloatingTerminalSettings = Pick<GlobalSettings, 'floatingTerminalTrustedCwds'>
type FloatingWorkspaceSettings = FloatingTerminalSettings &
Partial<Pick<GlobalSettings, 'floatingTerminalCwd'>>
const FLOATING_WORKSPACE_DIRNAME = 'floating-workspace'
@@ -38,17 +40,6 @@ function getTrustedFloatingWorkspaceDirectories(settings: FloatingTerminalSettin
)
}
async function getPreservedTrustedFloatingWorkspaceDirectories(
settings: GlobalSettings
): Promise<Set<string>> {
const trustedDirectories = new Set<string>()
for (const trustedDir of getTrustedFloatingWorkspaceDirectories(settings)) {
const canonicalDir = await canonicalizeAccessibleDirectory(trustedDir)
trustedDirectories.add(canonicalDir ?? trustedDir)
}
return trustedDirectories
}
function isTrustedFloatingWorkspaceDirectory(
canonicalDirPath: string,
settings: FloatingTerminalSettings
@@ -62,6 +53,58 @@ export function getDefaultFloatingWorkspacePath(): string {
return path.join(getAppEnvironment().getPath('userData'), FLOATING_WORKSPACE_DIRNAME)
}
let resolvedHomeCache: { home: string; real: string } | null = null
/** Home as spelled and as resolved through any link (e.g. /home -> /var/home), resolved once per home. */
function resolvedHome(): { home: string; real: string } {
const home = path.resolve(getAppEnvironment().getPath('home'))
if (resolvedHomeCache?.home !== home) {
let real = home
try {
real = path.resolve(realpathSync.native(home))
} catch {
// An unreadable home keeps its spelled path.
}
resolvedHomeCache = { home, real }
}
return resolvedHomeCache
}
/** A folder above home (such as `/`) was never what trusting a cwd meant; home itself, trusted explicitly, is. */
function isAboveHomeDirectory(dir: string): boolean {
const fold = (value: string): string =>
process.platform === 'linux' ? value : value.toLowerCase()
const { home: spelled, real } = resolvedHome()
return [spelled, real].some((home) => {
const rel = path.relative(fold(dir), fold(home))
return rel !== '' && rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)
})
}
/** Roots the floating workspace owns for file access; an untrusted cwd, or one above home, adds none. */
export function getFloatingWorkspaceFileRoots(store: {
getSettings(): FloatingWorkspaceSettings
}): {
extraRoots: string[]
exactRoots: string[]
} {
const settings = store.getSettings()
const configuredPath =
typeof settings.floatingTerminalCwd === 'string' ? settings.floatingTerminalCwd.trim() : ''
// Canonical home: trust entries are canonical, so `~` must expand to the spelling they store.
const cwd = configuredPath
? resolveFloatingWorkspacePath(configuredPath, resolvedHome().real)
: null
return {
extraRoots: [getDefaultFloatingWorkspacePath()],
// Exact: trusted entries are canonical, so a trusted cwd later replaced by a link fails closed.
exactRoots:
cwd && isTrustedFloatingWorkspaceDirectory(cwd, settings) && !isAboveHomeDirectory(cwd)
? [cwd]
: []
}
}
export async function ensureDefaultFloatingWorkspacePath(): Promise<string> {
const cwd = getDefaultFloatingWorkspacePath()
await mkdir(cwd, { recursive: true })
@@ -102,9 +145,8 @@ export async function trustFloatingWorkspaceDirectory(
if (!canonicalDir) {
return
}
const trustedDirectories = await getPreservedTrustedFloatingWorkspaceDirectories(
store.getSettings()
)
// Why spelling only for existing entries: re-resolving them would re-point a trusted folder since swapped for a link.
const trustedDirectories = getTrustedFloatingWorkspaceDirectories(store.getSettings())
trustedDirectories.add(canonicalDir)
store.updateSettings({
floatingTerminalTrustedCwds: [...trustedDirectories]
+2 -1
View File
@@ -42,7 +42,8 @@ export async function commitPtyIpcSpawn(ctx: PtyIpcSpawnState): Promise<PtySpawn
hasStablePaneOwner: ctx.stablePaneOwner !== null,
incarnationId: ctx.result.incarnationId
}),
launchedAgent: freshSpawn ? resolveLaunchedAgent(args.command, args.launchAgent) : null
launchedAgent: freshSpawn ? resolveLaunchedAgent(args.command, args.launchAgent) : null,
freshSpawn
},
preAllocatedHandle: ctx.preAllocatedHandle,
spawnTiming: ctx.spawnTiming,
@@ -20,7 +20,7 @@ import {
seedTerminalRestoreRecordsFromSpawnResult
} from './agent-session-owners'
import { seedHeadlessTerminalFromSpawnResult } from './terminal-spawn-restore'
import { admitProviderReattachLaunchIdentity } from './launch-authority'
import { admitProviderReattachLaunchIdentity, reattachLaunchBinding } from './launch-authority'
import { ensureWslHookRelayForReattach } from '../../../agent-hooks/wsl-relay/wsl-hook-relay-reattach'
import { wslBridgePtyPresence } from '../../../agent-hooks/wsl-relay/wsl-bridge-pty-presence'
import '../spawn-outcome'
@@ -138,7 +138,8 @@ export async function completePaneAdoption(
leafId: owner.leafId,
...(terminalHandle ? { terminalHandle } : {}),
...(result.incarnationId ? { incarnationId: result.incarnationId } : {}),
providerReattachLaunchIdentity: admitProviderReattachLaunchIdentity(result) ?? undefined
providerReattachLaunchIdentity: admitProviderReattachLaunchIdentity(result) ?? undefined,
...reattachLaunchBinding({ ...result, isReattach: true })
}
)
const response = provenSpawnResponse(
+18 -2
View File
@@ -1,3 +1,4 @@
import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol'
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config'
import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
@@ -13,7 +14,7 @@ export function admitRendererAgentLaunchAuthority(args: {
isReattach: boolean
hasStablePaneOwner: boolean
incarnationId: unknown
}): { launchToken: string; launchAgent: TuiAgent } | null {
}): { launchToken: string; launchAgent: TuiAgent; launchConfig: SleepingAgentLaunchConfig } | null {
if (
args.isReattach ||
args.hasStablePaneOwner ||
@@ -27,7 +28,22 @@ export function admitRendererAgentLaunchAuthority(args: {
) {
return null
}
return { launchToken: args.launchToken, launchAgent: args.launchAgent }
return {
launchToken: args.launchToken,
launchAgent: args.launchAgent,
launchConfig: args.launchConfig
}
}
/** A reattach's binding: its host's launch note, none when the host keeps no notes (an older daemon, SSH). */
export function reattachLaunchBinding(result: {
isReattach?: boolean
launchNote?: DaemonLaunchNote | null
}): { reattach?: { launchNote?: DaemonLaunchNote | null } } {
if (!result.isReattach) {
return {}
}
return { reattach: result.launchNote !== undefined ? { launchNote: result.launchNote } : {} }
}
export function admitProviderReattachLaunchIdentity(args: {
+7 -1
View File
@@ -1,6 +1,6 @@
import { adoptMaterializedRuntimePtySpawn } from './spawn-early'
import { createRuntimePtySpawnState } from './spawn-state'
import { getProviderForPty, localProvider } from '../provider/registry'
import { getProviderForPty, hasPtyProviderForInspection, localProvider } from '../provider/registry'
import {
getLocalAutomaticWorkStatus,
localTerminalLimit,
@@ -82,6 +82,12 @@ export function installPtyRuntimeController(deps: PtyRuntimeControllerDeps): voi
inspectProcess: (ptyId, options) => inspectProcessFromRuntimeController(ptyId, options),
confirmForegroundProcess: (ptyId) => confirmForegroundProcessFromRuntimeController(ptyId),
confirmShellForeground: (ptyId) => confirmShellForegroundFromRuntimeController(ptyId),
// Why local only: the daemon that outlives main is this host's.
setLaunchNote: (ptyId, change) => {
if (hasPtyProviderForInspection(ptyId)) {
getProviderForPty(ptyId).setLaunchNote?.(ptyId, change)
}
},
getCwd: (ptyId) => getCwdFromRuntimeController(ptyId),
hasChildProcesses: (ptyId) => hasChildProcessesFromRuntimeController(ptyId),
clearBuffer: (ptyId) => clearBufferFromRuntimeController(deps, ptyId),
+3 -1
View File
@@ -32,7 +32,9 @@ export async function commitRuntimePtySpawn(ctx: RuntimePtySpawnState) {
worktreeId: args.worktreeId,
shellOverride: ctx.daemonShellOverride,
rendererLaunchAuthority: null,
launchedAgent: null
launchedAgent: null,
// The runtime's own create records its launch once the spawn commits.
freshSpawn: false
},
preAllocatedHandle: args.preAllocatedHandle,
// Runtime spawns bypass renderer IPC; publish reverse pane lookup for hooks and cleanup.
+13 -4
View File
@@ -19,7 +19,11 @@ import {
} from './host-env/codex-home'
import { commitAttachedPtySize } from './delivery/attached-pty-size'
import { seedTerminalRestoreRecordsFromSpawnResult } from './pane/agent-session-owners'
import { admitProviderReattachLaunchIdentity } from './pane/launch-authority'
import {
admitProviderReattachLaunchIdentity,
reattachLaunchBinding,
type admitRendererAgentLaunchAuthority
} from './pane/launch-authority'
import type { ReplacedPaneOwner } from './pane/replaced-pane-owner'
import { admitPtySpawnOwnership, registerPersistedPtySpawn } from './pane/spawn-registration'
import type { PtySpawnOutcome } from './spawn-outcome'
@@ -90,9 +94,11 @@ export type PtySpawnCommitInput = {
store: Store | undefined
worktreeId: string | null | undefined
shellOverride: string | undefined
rendererLaunchAuthority: { launchToken: string; launchAgent: TuiAgent } | null
rendererLaunchAuthority: ReturnType<typeof admitRendererAgentLaunchAuthority>
/** The agent a fresh spawn's launch command starts; null for reattaches, adoptions and shells. */
launchedAgent: TuiAgent | null
/** Neither a reattach nor an adoption of a live pane's process. */
freshSpawn: boolean
}
preAllocatedHandle: string | null | undefined
spawnTiming?: PtySpawnTiming
@@ -162,7 +168,9 @@ export async function commitPtySpawn(input: PtySpawnCommitInput): Promise<PtySpa
? { agentLaunchAuthority: registration.rendererLaunchAuthority }
: {}),
...(registration.launchedAgent ? { launchedAgent: registration.launchedAgent } : {}),
...(providerReattachLaunchIdentity ? { providerReattachLaunchIdentity } : {})
...(providerReattachLaunchIdentity ? { providerReattachLaunchIdentity } : {}),
...(registration.freshSpawn ? { freshSpawn: true as const } : {}),
...reattachLaunchBinding(result)
}
: undefined,
shouldSkipCodexHomeEnvForWindowsShell(registration.shellOverride, state.cwd)
@@ -223,7 +231,8 @@ async function commitAdoptedAgentSession(
leafId: surface.leafId,
terminalHandle: surface.terminalHandle,
...(result.incarnationId ? { incarnationId: result.incarnationId } : {}),
...(providerReattachLaunchIdentity ? { providerReattachLaunchIdentity } : {})
...(providerReattachLaunchIdentity ? { providerReattachLaunchIdentity } : {}),
...reattachLaunchBinding(adoptedResult)
}
)
if (rejectedRegistration) {
@@ -22,6 +22,7 @@ import {
} from '../applying-settings/terminal-settings-migrations'
import {
canonicalizePersistedFloatingWorkspaceDirectory,
canonicalTrustedFloatingTerminalCwd,
normalizeFloatingWorkspaceTrustedCwds
} from '../restoring-sessions/floating-workspace-normalization'
@@ -151,7 +152,7 @@ export function prepareLoadedTerminalSettings(
const floatingTerminalCwdMigrated =
parsed.settings?.floatingTerminalCwdMigratedToAppWorkspace === true
// Repair the old empty notes-directory migration; terminal cwd and notes now resolve separately.
const migratedFloatingTerminalCwd = floatingTerminalCwdMigrated
const configuredFloatingTerminalCwd = floatingTerminalCwdMigrated
? !parsed.settings?.floatingTerminalCwd
? defaults.settings.floatingTerminalCwd
: parsed.settings.floatingTerminalCwd
@@ -186,6 +187,18 @@ export function prepareLoadedTerminalSettings(
if (normalizedFloatingTerminalTrustedCwds.changed) {
markNeedsSave()
}
// Why: settings are raw JSON here; a malformed cwd falls back to the default instead of failing reads.
const migratedFloatingTerminalCwd =
typeof configuredFloatingTerminalCwd === 'string'
? canonicalTrustedFloatingTerminalCwd(
configuredFloatingTerminalCwd,
migratedFloatingTerminalTrustedCwds,
homeDir
)
: defaults.settings.floatingTerminalCwd
if (migratedFloatingTerminalCwd !== configuredFloatingTerminalCwd) {
markNeedsSave()
}
return {
defaults,
migratedExternalVisibility,
@@ -16,13 +16,27 @@ export function canonicalizePersistedFloatingWorkspaceDirectory(
return null
}
try {
const canonicalPath = resolve(realpathSync(resolveFloatingWorkspacePath(trimmed, home)))
// Native: the on-disk spelling, as file authorization's realpath returns it on case-insensitive disks.
const canonicalPath = resolve(realpathSync.native(resolveFloatingWorkspacePath(trimmed, home)))
return statSync(canonicalPath).isDirectory() ? canonicalPath : null
} catch {
return null
}
}
/** Store a trusted cwd in its canonical spelling so file authorization can match it without I/O. */
export function canonicalTrustedFloatingTerminalCwd(
cwd: string,
trustedCwds: readonly string[],
home: string
): string {
if (cwd.trim() === '~') {
return cwd
}
const canonicalCwd = canonicalizePersistedFloatingWorkspaceDirectory(cwd, home)
return canonicalCwd && trustedCwds.includes(canonicalCwd) ? canonicalCwd : cwd
}
export function normalizeFloatingWorkspaceTrustedCwds(
input: unknown,
home: string
@@ -42,8 +56,9 @@ export function normalizeFloatingWorkspaceTrustedCwds(
changed = true
continue
}
const canonicalPath = canonicalizePersistedFloatingWorkspaceDirectory(trimmedTrustedCwd, home)
const normalizedPath = canonicalPath ?? resolveFloatingWorkspacePath(trimmedTrustedCwd, home)
// Spelling only, never through links: the approval-time realpath is the trusted root's identity,
// so a trusted folder later swapped for a link must not re-point its trust at the link's target.
const normalizedPath = resolveFloatingWorkspacePath(trimmedTrustedCwd, home)
if (!normalizedPath) {
changed = true
continue
@@ -0,0 +1,142 @@
import {
closeTestStores,
testState,
createStore,
writeDataFile,
readDataFile,
symlinkDirectorySync
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { getFloatingWorkspaceFileRoots } from '../../ipc/floating-workspace-directory'
import { rmSync, mkdtempSync, mkdirSync, realpathSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({
loadUserSshConfigMock: vi.fn(),
sshConfigHostsToTargetsMock: vi.fn()
}))
vi.mock('../../ssh/config/ssh-config-parser', () => ({
loadUserSshConfig: loadUserSshConfigMock,
sshConfigHostsToTargets: sshConfigHostsToTargetsMock
}))
const { trackMock, getCohortAtEmitMock } = vi.hoisted(() => ({
trackMock: vi.fn(),
getCohortAtEmitMock: vi.fn()
}))
vi.mock('electron', () => ({
app: {
getPath: () => testState.dir
},
safeStorage: {
isEncryptionAvailable: () => true,
encryptString: (plaintext: string) => Buffer.from(`encrypted:${plaintext}`, 'utf-8'),
decryptString: (ciphertext: Buffer) => {
const decoded = ciphertext.toString('utf-8')
if (!decoded.startsWith('encrypted:')) {
throw new Error('invalid ciphertext')
}
return decoded.slice('encrypted:'.length)
}
}
}))
vi.mock('../../telemetry/client', () => ({
track: trackMock
}))
vi.mock('../../telemetry/cohort-classifier', () => ({
getCohortAtEmit: getCohortAtEmitMock
}))
describe('floating workspace trust on load', () => {
beforeEach(() => {
testState.dir = mkdtempSync(join(tmpdir(), 'orca-test-'))
trackMock.mockReset()
getCohortAtEmitMock.mockReset()
getCohortAtEmitMock.mockReturnValue({ nth_repo_added: 2 })
})
afterEach(async () => {
await closeTestStores()
rmSync(testState.dir, { recursive: true, force: true })
})
it('seeds trust from a legacy explicit cwd and stores the cwd in that canonical spelling', async () => {
const legacyTarget = join(testState.dir, 'legacy-floating-target')
const legacyFloatingCwd = join(testState.dir, 'legacy-floating-cwd')
mkdirSync(legacyTarget)
symlinkDirectorySync(legacyTarget, legacyFloatingCwd)
const canonicalLegacyFloatingCwd = realpathSync(legacyTarget)
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
floatingTerminalCwd: legacyFloatingCwd
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
// File authorization matches the trusted cwd textually, so both must share one spelling.
expect(store.getSettings().floatingTerminalCwd).toBe(canonicalLegacyFloatingCwd)
expect(store.getSettings().floatingTerminalTrustedCwds).toEqual([canonicalLegacyFloatingCwd])
store.flush()
expect(readDataFile()).toMatchObject({
settings: { floatingTerminalTrustedCwds: [canonicalLegacyFloatingCwd] }
})
})
it('still loads a profile whose floating cwd is not a string', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
floatingTerminalCwd: 42,
floatingTerminalCwdMigratedToAppWorkspace: true
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().floatingTerminalCwd).toBe('~')
// File authorization reads the cwd on every check, so it must keep working for this profile.
expect(getFloatingWorkspaceFileRoots(store).exactRoots).toEqual([])
})
it('never re-points a trusted folder through a link on load', async () => {
const trustedTarget = join(testState.dir, 'trusted-target')
const trustedLink = join(testState.dir, 'trusted-link')
mkdirSync(trustedTarget)
symlinkDirectorySync(trustedTarget, trustedLink)
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
floatingTerminalTrustedCwds: [trustedLink]
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
// A trusted folder swapped for a link keeps its approved identity and fails closed (#36950).
expect(store.getSettings().floatingTerminalTrustedCwds).toEqual([trustedLink])
store.flush()
expect(readDataFile()).toMatchObject({
settings: { floatingTerminalTrustedCwds: [trustedLink] }
})
})
})
@@ -1,3 +1,4 @@
import type { DaemonLaunchNoteChange } from '../daemon/protocol/daemon-launch-note-protocol'
import type {
PtyFencedTerminationRequest,
PtyFencedTerminationOutcome
@@ -207,6 +208,8 @@ export type IPtyProvider = {
confirmForegroundProcess?: (id: string) => Promise<string | null>
/** Fresh execution-host proof that the spawned shell owns the PTY foreground. */
confirmShellForeground?: (id: string) => Promise<boolean>
/** Persist main's live launch where the PTY outlives main; only the daemon keeps one. */
setLaunchNote?: (id: string, change: DaemonLaunchNoteChange) => void
serialize(ids: string[]): Promise<string>
revive(state: string): Promise<void>
listProcesses(opts?: {
+3
View File
@@ -1,3 +1,4 @@
import type { DaemonLaunchNote } from '../daemon/protocol/daemon-launch-note-protocol'
import type { TerminalExitCause } from '../../shared/terminal/pty/lifecycle/terminal-exit-cause'
import type { TerminalLaunchResult } from '../../shared/agent-session/lifecycle/agent-session-resume'
import type { TerminalOscLinkRange } from '../../shared/terminal/links/terminal-osc-link-ranges'
@@ -25,6 +26,8 @@ export type PtySpawnResult = TerminalLaunchResult & {
pid?: number | null
/** Minimal allowlisted launch ownership returned by daemon reattach. */
launchAgent?: TuiAgent
/** The unretired launch main armed before a restart, returned by daemon reattach. */
launchNote?: DaemonLaunchNote | null
/** Local WSL context: null is native; undefined is unavailable/legacy. */
wslDistro?: string | null
/** Daemon reattach ANSI screen restore for xterm. */
@@ -0,0 +1,250 @@
import { describe, expect, it, vi } from 'vitest'
import { OrcaRuntimeService } from './orca-runtime'
import { makePaneKey } from '../../shared/workspace-layout/stable-pane-id'
const PTY_ID = 'pty-reattached'
const TAB_ID = '11111111-1111-4111-8111-111111111111'
const LEAF_ID = '22222222-2222-4222-8222-222222222222'
const INCARNATION = 'reattach-incarnation'
const LAUNCH_CONFIG = {
agentArgs: '--dangerously-skip-permissions --verbose',
agentEnv: { K: 'v' }
}
const NOTE = { launchToken: 'launch-1', launchConfig: LAUNCH_CONFIG }
const PANE_KEY = makePaneKey(TAB_ID, LEAF_ID)
function attach(
runtime: OrcaRuntimeService,
launchNote: typeof NOTE | null | undefined,
incarnationId = INCARNATION
) {
runtime.registerPty(PTY_ID, 'worktree-1', null, {
tabId: TAB_ID,
leafId: LEAF_ID,
incarnationId,
providerReattachLaunchIdentity: { incarnationId, launchAgent: 'claude' },
reattach: launchNote === undefined ? {} : { launchNote }
})
}
function holdLaunch(runtime: OrcaRuntimeService) {
runtime.registerPty(PTY_ID, 'worktree-1', null, {
tabId: TAB_ID,
leafId: LEAF_ID,
incarnationId: INCARNATION,
agentLaunchAuthority: {
launchToken: 'launch-1',
launchAgent: 'claude',
launchConfig: LAUNCH_CONFIG
}
})
}
// Some hosts register a spawn before they report its incarnation.
async function launchedBeforeItsIncarnation(foreground: 'agent' | 'unknown') {
const runtime = new OrcaRuntimeService(null)
Object.assign(runtime, {
resolveTerminalWorkspaceLaunchScope: async () => ({
id: 'worktree-1',
path: '/tmp/worktree-1',
connectionId: null
})
})
runtime.setPtyController({
write: vi.fn(() => true),
kill: vi.fn(),
getForegroundProcess: async () => null,
setLaunchNote: vi.fn(),
spawn: async () => {
runtime.registerPty(PTY_ID, 'worktree-1', null, { tabId: TAB_ID, leafId: LEAF_ID })
return { id: PTY_ID }
}
})
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground)
await runtime.createTerminal('id:worktree-1', {
tabId: TAB_ID,
leafId: LEAF_ID,
command: 'claude',
launchAgent: 'claude',
launchConfig: LAUNCH_CONFIG,
presentation: 'background'
})
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG)
return runtime
}
function makeRuntime() {
const runtime = new OrcaRuntimeService(null)
const setLaunchNote = vi.fn()
runtime.setPtyController({
write: vi.fn(() => true),
kill: vi.fn(),
getForegroundProcess: async () => null,
setLaunchNote
})
return { runtime, setLaunchNote }
}
async function reattach(
foreground: 'agent' | 'shell' | 'unknown',
mainHoldsLaunch = false,
launchNote: typeof NOTE | null | 'omitted' = NOTE,
finishedOnReattach = false
) {
const { runtime, setLaunchNote } = makeRuntime()
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue(foreground)
if (mainHoldsLaunch) {
holdLaunch(runtime)
}
attach(runtime, launchNote === 'omitted' ? undefined : launchNote)
await new Promise((resolve) => setTimeout(resolve, 0))
if (finishedOnReattach) {
attach(runtime, null)
}
return {
config: runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude'),
retired: setLaunchNote.mock.calls.some(([, change]) => 'retire' in change)
}
}
// Nothing reaches a daemon PTY while main is down, so only the same agent still running keeps the note.
describe('a daemon reattach after a main restart', () => {
it('re-arms the unretired launch while its agent still runs', async () => {
expect(await reattach('agent')).toEqual({ config: LAUNCH_CONFIG, retired: false })
})
it('says no launch runs when the foreground is the shell', async () => {
expect(await reattach('shell')).toEqual({ config: null, retired: true })
})
it('says no launch runs when the daemon retired its note', async () => {
expect((await reattach('agent', false, null)).config).toBeNull()
})
// Undecided: readers keep their earlier same-session rule rather than drop the settings.
it('makes no statement when the foreground is unreadable', async () => {
expect((await reattach('unknown')).config).toBeUndefined()
})
it('settles an undecided pane when a later attach reports its launch finished', async () => {
expect((await reattach('unknown', false, NOTE, true)).config).toBeNull()
})
it('makes no statement for a daemon that keeps no launch notes', async () => {
expect((await reattach('agent', false, 'omitted')).config).toBeUndefined()
})
it('settles an undecided pane once main sees its command finish', async () => {
const { runtime } = makeRuntime()
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('unknown')
attach(runtime, NOTE)
await new Promise((resolve) => setTimeout(resolve, 0))
runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 })
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
})
it('does not let an earlier foreground read revive a launch a later attach saw finish', async () => {
const { runtime } = makeRuntime()
let answer: (foreground: 'agent') => void = () => {}
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockReturnValue(
new Promise((resolve) => (answer = resolve))
)
attach(runtime, NOTE)
attach(runtime, null)
answer('agent')
await new Promise((resolve) => setTimeout(resolve, 0))
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
})
it('makes no statement for an older relay that reports no incarnation', () => {
const { runtime } = makeRuntime()
runtime.registerPty(PTY_ID, 'worktree-1', 'ssh-1', {
tabId: TAB_ID,
leafId: LEAF_ID,
reattach: {}
})
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeUndefined()
})
it('starts a replacement process decided even when its spawn is announced first', () => {
const { runtime } = makeRuntime()
const binding = { tabId: TAB_ID, leafId: LEAF_ID }
attach(runtime, undefined)
runtime.onPtySpawned(PTY_ID, 'next-incarnation')
runtime.registerPty(PTY_ID, 'worktree-1', null, {
...binding,
incarnationId: 'next-incarnation'
})
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
})
it('drops a held launch when a new process replaces it in the same terminal', () => {
const { runtime } = makeRuntime()
const binding = { tabId: TAB_ID, leafId: LEAF_ID }
holdLaunch(runtime)
runtime.onPtySpawned(PTY_ID, 'next-incarnation')
runtime.registerPty(PTY_ID, 'worktree-1', null, {
...binding,
incarnationId: 'next-incarnation'
})
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
})
// A finished launch stays finished for its process; only a fresh launch supersedes it.
it.each([
['a daemon that keeps no notes', undefined],
['a note the daemon has not retired', NOTE]
] as const)('keeps a finished launch gone when %s reattaches', async (_, launchNote) => {
const { runtime } = makeRuntime()
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent')
holdLaunch(runtime)
runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 })
attach(runtime, launchNote)
await new Promise((resolve) => setTimeout(resolve, 0))
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
})
it('lets a replacement process prove its own launch through a reattach', async () => {
const { runtime } = makeRuntime()
vi.spyOn(runtime, 'readLaunchedAgentForeground').mockResolvedValue('agent')
attach(runtime, undefined)
attach(runtime, NOTE, 'next-incarnation')
await new Promise((resolve) => setTimeout(resolve, 0))
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG)
})
// Learning the process's first incarnation is no replacement: what main knew still holds.
it.each([
['keeps no notes', undefined],
['still has the note', NOTE]
] as const)(
'keeps a launch that finished before its first incarnation gone when a host that %s attaches',
async (_, launchNote) => {
const runtime = await launchedBeforeItsIncarnation('agent')
runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 })
attach(runtime, launchNote)
await new Promise((resolve) => setTimeout(resolve, 0))
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toBeNull()
}
)
it.each([
['keeps no notes', undefined],
['sends the note late', NOTE]
] as const)(
'keeps a running launch when its first incarnation arrives from a host that %s',
async (_, launchNote) => {
const runtime = await launchedBeforeItsIncarnation('unknown')
attach(runtime, launchNote)
await new Promise((resolve) => setTimeout(resolve, 0))
expect(runtime.getLaunchStatementForPaneKey(PANE_KEY, 'claude')).toEqual(LAUNCH_CONFIG)
}
)
// The renderer attaches a pane the CLI launched before its agent has started.
it('leaves a launch main already holds when the attach still sees its shell', async () => {
expect(await reattach('shell', true)).toEqual({ config: LAUNCH_CONFIG, retired: false })
})
})
@@ -0,0 +1,128 @@
import { mkdir, mkdtemp, realpath, rename, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { installFakeAppEnvironment } from '../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup'
import type { RuntimeStore } from '../construction/runtime-store-contract'
import { invalidateAuthorizedRootsCache } from '../../ipc/worktrees/removal/registered-worktree-roots-cache'
import { resolveRuntimeAuthorizedPath } from './chat-scratch-file-root'
let base: string
let home: string
let project: string
function storeWithFloatingCwd(cwd: string, trusted: string[]): RuntimeStore {
const settings = {
workspaceDir: '',
nestWorkspaces: false,
floatingTerminalCwd: cwd,
floatingTerminalTrustedCwds: trusted
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: authorization reads only these members.
return {
getRepos: () => [],
getProjectGroups: () => [],
getFolderWorkspaces: () => [],
getSettings: () => settings
} as unknown as RuntimeStore
}
beforeEach(async () => {
invalidateAuthorizedRootsCache()
base = await realpath(await mkdtemp(join(tmpdir(), 'orca-runtime-floating-root-')))
home = join(base, 'home')
project = join(base, 'project')
await mkdir(home)
await mkdir(project)
await writeFile(join(home, 'secret.txt'), 'x')
await writeFile(join(project, 'index.html'), 'x')
installFakeAppEnvironment({
getPath: (name) => (name === 'home' ? home : join(base, 'user-data'))
})
})
afterEach(async () => {
await rm(base, { recursive: true, force: true })
})
describe('runtime file authorization for the floating workspace', () => {
it('authorizes files in a trusted floating cwd', async () => {
const store = storeWithFloatingCwd(project, [project])
await expect(resolveRuntimeAuthorizedPath(join(project, 'index.html'), store)).resolves.toBe(
join(project, 'index.html')
)
})
// #36950 as reported: `orca serve` with the floating cwd at a trusted project under home.
it('authorizes a file in a trusted cwd spelled from home', async () => {
const app = join(home, 'projects', 'my-app')
await mkdir(app, { recursive: true })
await writeFile(join(app, 'index.html'), 'x')
const store = storeWithFloatingCwd('~/projects/my-app', [app])
await expect(resolveRuntimeAuthorizedPath(join(app, 'index.html'), store)).resolves.toBe(
join(app, 'index.html')
)
})
it('does not authorize an untrusted floating cwd or the home default', async () => {
await expect(
resolveRuntimeAuthorizedPath(join(project, 'index.html'), storeWithFloatingCwd(project, []))
).rejects.toThrow(/outside allowed directories/)
for (const cwd of ['', '~']) {
await expect(
resolveRuntimeAuthorizedPath(join(home, 'secret.txt'), storeWithFloatingCwd(cwd, []))
).rejects.toThrow(/outside allowed directories/)
}
})
it('authorizes an explicitly trusted home, but never a folder above it', async () => {
for (const cwd of [home, '~']) {
await expect(
resolveRuntimeAuthorizedPath(join(home, 'secret.txt'), storeWithFloatingCwd(cwd, [home]))
).resolves.toBe(join(home, 'secret.txt'))
}
await expect(
resolveRuntimeAuthorizedPath(join(home, 'secret.txt'), storeWithFloatingCwd(base, [base]))
).rejects.toThrow(/outside allowed directories/)
})
it('matches a trusted ~ when home itself is reached through a link', async () => {
const linkedHome = join(base, 'linked-home')
await symlink(home, linkedHome, process.platform === 'win32' ? 'junction' : 'dir')
installFakeAppEnvironment({
getPath: (name) => (name === 'home' ? linkedHome : join(base, 'user-data'))
})
const store = storeWithFloatingCwd('~', [home])
await expect(resolveRuntimeAuthorizedPath(join(home, 'secret.txt'), store)).resolves.toBe(
join(home, 'secret.txt')
)
})
// Byte-exact names (ext4) let an NFC root be swapped for a link to a distinct NFD-named folder.
it.skipIf(process.platform !== 'linux')(
'does not follow a trusted cwd swapped for a link to a Unicode-equivalent folder',
async () => {
const approved = join(base, 'caf\u00e9')
const lookalike = join(base, 'cafe\u0301')
await mkdir(approved)
await mkdir(lookalike)
await writeFile(join(lookalike, 'index.html'), 'x')
const store = storeWithFloatingCwd(approved, [approved])
await rm(approved, { recursive: true })
await symlink(lookalike, approved, 'dir')
await expect(
resolveRuntimeAuthorizedPath(join(lookalike, 'index.html'), store)
).rejects.toThrow(/outside allowed directories/)
}
)
it('does not follow a trusted cwd that was replaced by a link elsewhere', async () => {
const elsewhere = join(base, 'elsewhere')
await rename(project, elsewhere)
await symlink(elsewhere, project, process.platform === 'win32' ? 'junction' : 'dir')
const store = storeWithFloatingCwd(project, [project])
await expect(resolveRuntimeAuthorizedPath(join(project, 'index.html'), store)).rejects.toThrow(
/outside allowed directories/
)
})
})
@@ -8,6 +8,7 @@ import {
import { isENOENT } from '../../ipc/filesystem/access/filesystem-path-containment'
import { nativeChatScratchRootFor } from '../../native-chat/native-chat-scratch-folder'
import { getProfileUserDataPath } from '../../orca-profiles/profile-storage-paths'
import { getFloatingWorkspaceFileRoots } from '../../ipc/floating-workspace-directory'
const PATH_SELECTOR_PREFIX = 'path:'
const SCRATCH_FOLDER_NAME = /^[0-9a-f]{32}$/
@@ -21,7 +22,12 @@ export function resolveRuntimeAuthorizedPath(
store: RuntimeStore,
options: ResolveAuthorizedPathOptions = {}
): Promise<string> {
return resolveAuthorizedPath(targetPath, store, { ...options, extraRoots: [chatScratchRoot()] })
const floating = getFloatingWorkspaceFileRoots(store)
return resolveAuthorizedPath(targetPath, store, {
...options,
extraRoots: [chatScratchRoot(), ...floating.extraRoots],
exactRoots: floating.exactRoots
})
}
export function isChatScratchWorktreeId(worktreeId: string): boolean {
@@ -69,7 +69,8 @@ function createWindowsWatcher(close: () => void) {
}
function createRuntimeFileWatches(rootPath: string) {
const store = { getRepo: vi.fn(() => undefined) }
// getSettings: file authorization reads the floating cwd; this store trusts none.
const store = { getRepo: vi.fn(() => undefined), getSettings: () => ({}) }
const commands = new RuntimeFileWatches({
getRuntimeId: () => 'runtime-1',
requireStore: () => store,
@@ -0,0 +1,102 @@
import { describe, expect, it, vi } from 'vitest'
import { EnsureAgentSessionParams } from '../../shared/rpc-contract/agent-session-params'
import type { AgentStatusIpcPayload } from '../../shared/agent-status/contracts/agent-status-ipc-payload'
import { OrcaRuntimeService } from './orca-runtime'
import { partialRuntimeStore } from './orca-runtime-tests/runtime-store-partial-fixture'
const TAB = '11111111-1111-4111-8111-111111111111'
const SOURCE_PANE = `${TAB}:22222222-2222-4222-8222-222222222222`
const NEW_TAB = '33333333-3333-4333-8333-333333333333'
const NEW_LEAF = '44444444-4444-4444-8444-444444444444'
const SESSION = { key: 'session_id', id: 'conversation-1' } as const
function restoreOnHost(args: {
recorded?: { agentArgs: string; agentEnv: Record<string, string> }
hookMode?: string
}) {
const runtime = new OrcaRuntimeService(
partialRuntimeStore({
getSettings: () => ({
disabledTuiAgents: [],
agentCmdOverrides: {},
agentDefaultArgs: { claude: '--model current' },
agentDefaultEnv: { claude: { CURRENT: '1' } }
})
})
)
const record = {
paneKey: SOURCE_PANE,
worktreeId: 'worktree-1',
agent: 'claude' as const,
providerSession: SESSION,
prompt: '',
state: 'done' as const,
capturedAt: 1,
updatedAt: 1,
...(args.recorded ? { launchConfig: args.recorded } : {})
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the host's restore reads only the row's pane, agent and provider session.
const hookRow = {
paneKey: SOURCE_PANE,
agentType: 'claude',
providerSession: { ...SESSION, permissionMode: args.hookMode }
} as AgentStatusIpcPayload
Object.assign(runtime, {
resolveTerminalWorkspaceLaunchScope: vi.fn(async () => ({
id: 'worktree-1',
path: '/tmp/worktree-1',
connectionId: null
})),
getWorkspaceSessionForWorktree: () => ({
sleepingAgentSessionsByPaneKey: { [SOURCE_PANE]: record }
}),
getAgentProviderSessionSnapshotFn: () => [hookRow]
})
const createTerminal = vi.spyOn(runtime, 'createTerminal').mockResolvedValue({
handle: 'term_restore',
tabId: NEW_TAB,
paneKey: `${NEW_TAB}:${NEW_LEAF}`,
ptyId: 'pty-restore',
worktreeId: 'worktree-1',
title: null,
surface: 'background'
})
return {
restore: () =>
runtime.ensureAgentSession(
EnsureAgentSessionParams.parse({
kind: 'explicit',
resumeOrigin: 'saved',
restoreSourcePaneKey: SOURCE_PANE,
worktree: 'id:worktree-1',
agent: 'claude',
providerSession: SESSION,
agentArgs: '--model client',
placement: { tabId: NEW_TAB, leafId: NEW_LEAF }
})
),
launched: () => createTerminal.mock.calls[0]?.[1]
}
}
// A Wake opens a new tab: the host must replay the pane that ran, not the new pane or its own settings.
describe('a saved restore into a new pane on its host', () => {
it("replays the source pane's note", async () => {
const host = restoreOnHost({
recorded: { agentArgs: '--verbose', agentEnv: { RECORDED: '1' } }
})
await host.restore()
expect(host.launched()?.command).toContain('--verbose')
expect(host.launched()?.command).not.toContain('--model')
expect(host.launched()?.env).toMatchObject({ RECORDED: '1' })
expect(host.launched()?.env).not.toHaveProperty('CURRENT')
})
it("without a note, keeps only the bypass the host's hooks saw, never current settings", async () => {
const host = restoreOnHost({ hookMode: 'bypassPermissions' })
await host.restore()
expect(host.launched()?.command).toContain('--dangerously-skip-permissions')
expect(host.launched()?.command).not.toContain('--model')
expect(host.launched()?.env).not.toHaveProperty('CURRENT')
})
})
@@ -1,8 +1,10 @@
import { sleepingAgentLaunchConfigSchema } from '../../../../../shared/workspace-session/workspace-session-sleeping-agents'
import { resolveWorkerLineageFacts, FOLLOW_UP_MESSAGE_TYPES } from './worker-follow-up-plan'
import {
normalizeAgentProviderSession,
type AgentProviderSessionMetadata
type AgentProviderSessionMetadata,
type SleepingAgentLaunchConfig
} from '../../../../../shared/agent-session/lifecycle/agent-session-resume'
import {
getConnectionExecutionHostId,
@@ -23,6 +25,8 @@ export type WorkerResumeSession = {
agent: TuiAgent
providerSession: AgentProviderSessionMetadata
captureHostId: ExecutionHostId
/** The recipe the worker launched with; its pane's own record is gone once it closes (#37693). */
launchConfig?: SleepingAgentLaunchConfig
}
export function getFollowUpDispatch(
@@ -84,10 +88,18 @@ export function readWorkerResumeSession(
const providerSession = normalizeAgentProviderSession(
'providerSession' in parsed ? parsed.providerSession : undefined
)
const launchConfig = sleepingAgentLaunchConfigSchema.parse(
'launchConfig' in parsed ? parsed.launchConfig : undefined
)
return isTuiAgent(agent) &&
providerSession &&
(connectionId === null || typeof connectionId === 'string')
? { agent, providerSession, captureHostId: getConnectionExecutionHostId(connectionId) }
? {
agent,
providerSession,
captureHostId: getConnectionExecutionHostId(connectionId),
...(launchConfig ? { launchConfig } : {})
}
: null
} catch {
return null
@@ -107,10 +119,12 @@ export function recordWorkerResumeSession(
const connectionId = isLocalHookConnectionId(session.connectionId)
? null
: (session.connectionId ?? null)
const { launchConfig } = session
const value = JSON.stringify({
agent: session.agent,
providerSession: session.providerSession,
connectionId
connectionId,
...(launchConfig ? { launchConfig } : {})
})
// A repeat of the stored conversation writes nothing.
db.db
@@ -48,7 +48,7 @@ async function hashAsset(root: string, asset: MobileWebBundleAsset): Promise<boo
/** Fill a manifest-bounded window; early EOF means asset-changed, never a short page. Packaged bundles are unpacked, so positional reads need no file cache (#27976). */
export async function readMobileWebBundleAssetWindow(
root: string,
asset: MobileWebBundleAsset,
asset: Pick<MobileWebBundleAsset, 'path' | 'byteLength'>,
offset: number,
length: number
): Promise<Buffer> {
@@ -2,11 +2,13 @@ import { randomBytes } from 'node:crypto'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { gunzipSync } from 'node:zlib'
import { brotliDecompressSync, gunzipSync } from 'node:zlib'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD,
MOBILE_WEB_BUNDLE_CHUNK_BYTES as RANGE_BYTES,
MOBILE_WEB_BUNDLE_RANGE_METHOD,
MobileWebBundleBrotliRangeResultSchema,
MobileWebBundleRangeResultSchema,
type MobileWebBundleRangeResult
} from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract'
@@ -140,3 +142,68 @@ describe('mobileWeb.bundle.range on an install that carries a bundle', () => {
).toBe(true)
})
})
describe('mobileWeb.bundle.brotliRange', () => {
// Base64 text shrinks only to about 3/4, so its copy spans several windows.
const SCRIPT: SyntheticAsset = (() => {
const bytes = Buffer.from(randomBytes(RANGE_BYTES * 2).toString('base64'))
return {
path: `assets/${sha256Hex(bytes)}.js`,
bytes,
contentType: 'text/javascript',
brotli: true
}
})()
let bundle: SyntheticMobileWebBundle
beforeEach(() => {
bundle = writeSyntheticMobileWebBundle(join(scratch, 'out', 'mobile-web'), 1, [
SCRIPT,
INCOMPRESSIBLE
])
})
it('pages the brotli copy on the range grid, and the pages inflate to the asset', async () => {
const entry = bundle.assets.find((asset) => asset.path === SCRIPT.path)
const copyLength = entry?.brotliByteLength ?? 0
expect(copyLength).toBeGreaterThan(0)
const pieces: Buffer[] = []
for (let offset = 0; ; offset += RANGE_BYTES) {
const response = await call(MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD, {
buildId: bundle.buildId,
path: SCRIPT.path,
offset
})
if (!response.ok) {
throw new Error(response.error.message)
}
const result = MobileWebBundleBrotliRangeResultSchema.parse(response.result)
expect(result).toMatchObject({
path: SCRIPT.path,
offset,
assetByteLength: SCRIPT.bytes.byteLength,
sha256: sha256Hex(SCRIPT.bytes),
eof: offset + RANGE_BYTES >= copyLength
})
pieces.push(Buffer.from(result.dataBase64, 'base64'))
if (result.eof) {
break
}
}
expect(pieces.length).toBe(Math.ceil(copyLength / RANGE_BYTES))
expect(pieces.length).toBeGreaterThan(1)
expect(Buffer.concat(pieces).byteLength).toBe(copyLength)
expect(brotliDecompressSync(Buffer.concat(pieces)).equals(SCRIPT.bytes)).toBe(true)
})
it('refuses an asset the manifest gives no brotli copy', async () => {
const response = await call(MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD, {
buildId: bundle.buildId,
path: INCOMPRESSIBLE.path,
offset: 0
})
expect(response.ok).toBe(false)
expect(response.ok ? null : response.error.message).toBe('mobile_web_bundle_asset_unknown')
})
})
@@ -1,6 +1,7 @@
import { createHash } from 'node:crypto'
import { mkdirSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { brotliCompressSync } from 'node:zlib'
import { installFakeAppEnvironment } from '../../../../../../config/scripts/test-runtime/environment/vitest-host-ports-setup'
import type { OrcaRuntimeService } from '../../../orca-runtime'
import { RpcDispatcher } from '../../dispatcher'
@@ -8,6 +9,7 @@ import { MOBILE_WEB_BUNDLE_METHODS } from './mobile-web-bundle'
import { MOBILE_WEB_BUNDLE_CHUNK_BYTES } from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract'
import {
computeMobileWebBundleId,
mobileWebBundleBrotliPath,
type MobileWebBundleAsset
} from '../../../../../shared/mobile-web-bundle/manifest-contract'
@@ -22,7 +24,8 @@ export function mobileWebBundleFiller(byteLength: number, seed: number): Buffer
return bytes
}
export type SyntheticAsset = { path: string; bytes: Buffer; contentType: string }
/** `brotli` writes the asset's brotli copy and lists its length, as the shipped build does. */
export type SyntheticAsset = { path: string; bytes: Buffer; contentType: string; brotli?: boolean }
/** Use synthetic multi-chunk assets because the current builder emits smaller files and CI unit jobs do not build the bundle. */
function syntheticAssets(seed: number): SyntheticAsset[] {
@@ -58,15 +61,22 @@ export function writeSyntheticMobileWebBundle(
): SyntheticMobileWebBundle {
mkdirSync(join(root, 'assets'), { recursive: true })
const written = [...syntheticAssets(seed), ...extraAssets]
const copies = new Map<string, Buffer>()
for (const asset of written) {
writeFileSync(join(root, asset.path), asset.bytes)
if (asset.brotli === true) {
const copy = brotliCompressSync(asset.bytes)
writeFileSync(join(root, mobileWebBundleBrotliPath(asset.path)), copy)
copies.set(asset.path, copy)
}
}
const assets = written
.map((asset) => ({
path: asset.path,
sha256: sha256Hex(asset.bytes),
byteLength: asset.bytes.byteLength,
contentType: asset.contentType
contentType: asset.contentType,
...(copies.has(asset.path) ? { brotliByteLength: copies.get(asset.path)?.byteLength } : {})
}))
.sort((left, right) => (left.path < right.path ? -1 : 1))
const buildId = computeMobileWebBundleId(assets)
@@ -2,19 +2,24 @@
* Never proxy to SSH/relay execution hosts: the phone paired with this desktop.
* Verify/read failures map to asset-changed without exposing host paths. */
import {
MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD,
MOBILE_WEB_BUNDLE_CHUNK_BYTES,
MOBILE_WEB_BUNDLE_CHUNK_METHOD,
MOBILE_WEB_BUNDLE_MANIFEST_METHOD,
MOBILE_WEB_BUNDLE_RANGE_METHOD,
MobileWebBundleChunkParamsSchema,
MobileWebBundleRangeParamsSchema,
type MobileWebBundleBrotliRangeResult,
type MobileWebBundleChunkParams,
type MobileWebBundleChunkResult,
type MobileWebBundleErrorCode,
type MobileWebBundleManifestResult,
type MobileWebBundleRangeResult
} from '../../../../../shared/mobile-web-bundle/bundle-rpc-contract'
import type { MobileWebBundleAsset } from '../../../../../shared/mobile-web-bundle/manifest-contract'
import {
mobileWebBundleBrotliPath,
type MobileWebBundleAsset
} from '../../../../../shared/mobile-web-bundle/manifest-contract'
import {
loadBundledMobileWebBundle,
type BundledMobileWebBundle
@@ -72,16 +77,27 @@ function findAsset(bundle: BundledMobileWebBundle, path: string): MobileWebBundl
function assertOffsetAddressesAWindow(
offset: number,
windowBytes: number,
asset: MobileWebBundleAsset
file: WindowSource
): void {
if (offset % windowBytes !== 0) {
throw bundleError('mobile_web_bundle_offset_invalid')
}
if (offset > 0 && offset >= asset.byteLength) {
if (offset > 0 && offset >= file.byteLength) {
throw bundleError('mobile_web_bundle_offset_invalid')
}
}
/** The file a window is cut from: the asset itself, or its brotli copy. */
type WindowSource = Pick<MobileWebBundleAsset, 'path' | 'byteLength'>
/** Only assets the manifest gives a copy have one; asking for another is asking for an unlisted file. */
function brotliCopyOf(asset: MobileWebBundleAsset): WindowSource {
if (asset.brotliByteLength === undefined) {
throw bundleError('mobile_web_bundle_asset_unknown')
}
return { path: mobileWebBundleBrotliPath(asset.path), byteLength: asset.brotliByteLength }
}
/** The self-description every chunk or range reply carries, plus the raw bytes of its window. */
type VerifiedWindow = {
header: Omit<MobileWebBundleChunkResult, 'dataBase64'>
@@ -93,7 +109,8 @@ async function readVerifiedWindow<T>(
ctx: RpcContext,
params: MobileWebBundleChunkParams,
windowBytes: number,
encode: (window: VerifiedWindow) => Promise<T>
encode: (window: VerifiedWindow) => Promise<T>,
sourceOf: (asset: MobileWebBundleAsset) => WindowSource = (asset) => asset
): Promise<T> {
const bundle = requireBundle()
// Check build before path: auto-update means restart from the manifest, not missing-asset.
@@ -101,7 +118,8 @@ async function readVerifiedWindow<T>(
throw bundleError('mobile_web_bundle_build_changed')
}
const asset = findAsset(bundle, params.path)
assertOffsetAddressesAWindow(params.offset, windowBytes, asset)
const source = sourceOf(asset)
assertOffsetAddressesAWindow(params.offset, windowBytes, source)
const release = acquireMobileWebBundleReadSlot(mobileWebBundleReadBucket(ctx))
if (!release) {
@@ -115,7 +133,7 @@ async function readVerifiedWindow<T>(
abortIfDisconnected(ctx)
const data = await readMobileWebBundleAssetWindow(
bundle.root,
asset,
source,
params.offset,
windowBytes
)
@@ -127,7 +145,7 @@ async function readVerifiedWindow<T>(
offset: params.offset,
assetByteLength: asset.byteLength,
sha256: asset.sha256,
eof: params.offset + data.byteLength >= asset.byteLength
eof: params.offset + data.byteLength >= source.byteLength
},
data
})
@@ -138,6 +156,11 @@ async function readVerifiedWindow<T>(
}
}
/** Chunks and brotli windows go out as read: chunks predate encodings, and brotli output does not shrink again. */
async function rawWindowReply(window: VerifiedWindow): Promise<MobileWebBundleChunkResult> {
return { ...window.header, dataBase64: window.data.toString('base64') }
}
export const MOBILE_WEB_BUNDLE_METHODS = [
defineMethod({
name: MOBILE_WEB_BUNDLE_MANIFEST_METHOD,
@@ -155,10 +178,7 @@ export const MOBILE_WEB_BUNDLE_METHODS = [
permission: 'workspace',
params: MobileWebBundleChunkParamsSchema,
handler: (params, ctx): Promise<MobileWebBundleChunkResult> =>
readVerifiedWindow(ctx, params, MOBILE_WEB_BUNDLE_CHUNK_BYTES, async (window) => ({
...window.header,
dataBase64: window.data.toString('base64')
}))
readVerifiedWindow(ctx, params, MOBILE_WEB_BUNDLE_CHUNK_BYTES, rawWindowReply)
}),
defineMethod({
name: MOBILE_WEB_BUNDLE_RANGE_METHOD,
@@ -173,5 +193,13 @@ export const MOBILE_WEB_BUNDLE_METHODS = [
dataBase64: encoded.bytes.toString('base64')
}
})
}),
defineMethod({
name: MOBILE_WEB_BUNDLE_BROTLI_RANGE_METHOD,
permission: 'workspace',
params: MobileWebBundleRangeParamsSchema,
handler: (params, ctx): Promise<MobileWebBundleBrotliRangeResult> =>
// The raw asset's hash still gates every window of its copy.
readVerifiedWindow(ctx, params, MOBILE_WEB_BUNDLE_CHUNK_BYTES, rawWindowReply, brotliCopyOf)
})
]
@@ -1,3 +1,4 @@
import { resolveResumeLaunchRecipe } from '../../../../../../shared/agent-launch/choices/resume-launch-recipe'
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
@@ -50,6 +51,12 @@ export async function reopenWorkerTerminal(
): Promise<ReopenedWorker | null> {
const resumed = await runtime.resumeAgentSessionInWorkspace(worktreeId, {
...session,
// Why always a recipe: without its own note the worker resumes unrecorded, never with another pane's.
launchConfig: resolveResumeLaunchRecipe(
session.launchConfig,
session.agent,
session.providerSession
),
// A retry of this follow-up reconciles the pane it may have started.
mutationId: dispatchId
})
@@ -3,6 +3,7 @@ import { ORCA_SIDEBAR_INPUTS_IS_MAIN } from '../../../../shared/sidebar-inputs-s
/** Phone methods the relaying Mac always answers itself, even when the call names a server. */
export const PAIRED_DESKTOP_METHODS = [
// Device and pairing concerns of the phone's own pairing.
'mobileWeb.bundle.brotliRange',
'mobileWeb.bundle.chunk',
'mobileWeb.bundle.manifest',
'mobileWeb.bundle.range',
@@ -18,6 +18,10 @@ import { agentLaunchQuotingShell } from '../../../../shared/agent-launch/startup
import { OrchestrationError } from '../../orchestration/orchestration-error'
import { withAgentSessionAccountEnv } from '../../agent-session/agent-session-account-env'
import { resolveWslHostAgentResumeInputs } from '../../terminal/launch/wsl-host-agent-terminal-launch'
import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import { resolveSavedRestoreLaunchRecipe } from './saved-restore-launch-recipe'
import { worktreeIdsEqual } from '../../../../shared/worktree/id'
import {
resolveTuiAgentLaunchRawArgs,
resolveTuiAgentLaunchEnv
@@ -86,6 +90,34 @@ export abstract class OrcaRuntimeWithGetAgentSessionExecutionNamespace extends O
return Object.keys(options).length > 0 ? options : undefined
}
/** A saved restore replays the source pane as this host ran it; History and other user resumes keep current settings. */
private savedRestoreRecipe(
worktreeId: string,
request: Extract<RuntimeEnsureAgentSessionRequest, { kind: 'explicit' }>
): SleepingAgentLaunchConfig {
// Why the source pane: a Wake opens a new tab, so `placement` names a pane that never ran it.
const { tabId, leafId } = request.placement ?? {}
const sourcePaneKey =
request.restoreSourcePaneKey ??
// A legacy non-UUID leaf names no saved record, so it gets the no-note rule instead of throwing.
(tabId && !tabId.includes(':') && leafId && isTerminalLeafId(leafId)
? makePaneKey(tabId, leafId)
: null)
const record = sourcePaneKey
? this.getWorkspaceSessionForWorktree(worktreeId)?.sleepingAgentSessionsByPaneKey?.[
sourcePaneKey
]
: undefined
return resolveSavedRestoreLaunchRecipe({
agent: request.agent,
providerSession: request.providerSession,
record: record && worktreeIdsEqual(record.worktreeId, worktreeId) ? record : undefined,
liveRow: sourcePaneKey
? this.getAgentProviderSessionSnapshotFn?.().find((row) => row.paneKey === sourcePaneKey)
: undefined
})
}
async ensureAgentSession(
request: RuntimeEnsureAgentSessionRequest,
_caller: RuntimeAgentSessionRpcCaller = {}
@@ -134,17 +166,21 @@ export abstract class OrcaRuntimeWithGetAgentSessionExecutionNamespace extends O
const shell = agentLaunchQuotingShell(launchRuntime)
// Use the resolved PTY route, not display repo metadata that may belong to another host.
const isRemote = Boolean(workspace.connectionId)
const restored =
request.resumeOrigin === 'saved' ? this.savedRestoreRecipe(workspace.id, request) : undefined
const startup = buildAgentResumeStartupPlan(
resolveWslHostAgentResumeInputs({
agent: request.agent,
providerSession: identity.providerSession,
cmdOverrides: settings.agentCmdOverrides ?? {},
agentArgs:
request.agentArgs !== undefined
? request.agentArgs
: resolveTuiAgentLaunchRawArgs(request.agent, settings, undefined, shell),
agentEnv: resolveTuiAgentLaunchEnv(request.agent, settings),
ompResumeFilePath: request.ompResumeFilePath,
...(restored ?? {
agentArgs:
request.agentArgs !== undefined
? request.agentArgs
: resolveTuiAgentLaunchRawArgs(request.agent, settings, undefined, shell),
agentEnv: resolveTuiAgentLaunchEnv(request.agent, settings)
}),
ompResumeFilePath: restored?.ompResumeFilePath ?? request.ompResumeFilePath,
sessionOptions: this.toAgentSessionOptions(request.launchPreferences),
sessionOptionsOverrideAgentArgs: Boolean(request.launchPreferences),
platform,
@@ -0,0 +1,35 @@
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import { resolveResumeLaunchRecipe } from '../../../../shared/agent-launch/choices/resume-launch-recipe'
import {
agentProviderSessionsEqual,
normalizeAgentProviderSession,
type AgentProviderSessionMetadata,
type SleepingAgentLaunchConfig,
type SleepingAgentSessionRecord
} from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
/** The source pane's note on this host, else the unrecorded rule; never current settings or client Arguments. */
export function resolveSavedRestoreLaunchRecipe(args: {
agent: TuiAgent
providerSession: AgentProviderSessionMetadata
/** The source pane's record and latest status on this host. */
record: SleepingAgentSessionRecord | undefined
liveRow: AgentStatusIpcPayload | undefined
}): SleepingAgentLaunchConfig {
const { agent } = args
const sameSession = (session: AgentProviderSessionMetadata | null | undefined) =>
session && agentProviderSessionsEqual(agent, session, args.providerSession) ? session : null
const recorded =
args.record?.agent === agent && sameSession(args.record.providerSession)
? args.record
: undefined
if (recorded?.launchConfig) {
return resolveResumeLaunchRecipe(recorded.launchConfig, agent, recorded.providerSession)
}
const live =
args.liveRow?.agentType === agent
? sameSession(normalizeAgentProviderSession(args.liveRow.providerSession))
: null
return resolveResumeLaunchRecipe(undefined, agent, live ?? recorded?.providerSession)
}
@@ -1,18 +1,22 @@
import type { AgentStatusEntry } from '../../../../shared/agent-status/contracts/agent-status-types'
import { launchStatement, type PtyLaunchFacts } from '../../terminal/launch/launch-evidence'
/** A pane's projected agent status as a session-tabs frame publishes it. The frame names its
* worktree on every agent: a restored row without a live PTY names none, and clients decide row
* ownership (and retraction) by worktree. The turn stamp travels on the tab, not the status. */
* ownership (and retraction) by worktree. The turn stamp and owner's launch fact travel on the tab. */
export function frameAgentStatus(
projected: (AgentStatusEntry & { turnCompletedAt?: number }) | undefined,
worktreeId: string
): { agentStatus?: AgentStatusEntry; projectedTurnCompletedAt?: number } {
worktreeId: string,
pty?: PtyLaunchFacts | null
): { agentStatus?: AgentStatusEntry; projectedTurnCompletedAt?: number; launchAttested?: boolean } {
if (!projected) {
return {}
}
const { turnCompletedAt, ...fields } = projected
const statement = pty ? launchStatement(pty, fields.agentType) : undefined
return {
agentStatus: { ...fields, worktreeId },
...(statement !== undefined ? { launchAttested: statement !== null } : {}),
...(turnCompletedAt !== undefined ? { projectedTurnCompletedAt: turnCompletedAt } : {})
}
}
@@ -3,7 +3,8 @@ import { makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import {
agentProviderSessionsEqual,
normalizeAgentProviderSession,
type AgentProviderSessionMetadata
type AgentProviderSessionMetadata,
type SleepingAgentLaunchConfig
} from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import {
@@ -46,6 +47,8 @@ export abstract class OrcaRuntimeWithResumeAgentSessionInWorkspace extends OrcaR
captureHostId: ExecutionHostId
/** Names the new pane, so a retry of one request reconciles the pane it may have started. */
mutationId: string
/** The caller's complete recipe; without one, the conversation's own pane record supplies it. */
launchConfig?: SleepingAgentLaunchConfig
signal?: AbortSignal
}
): Promise<AgentSessionResumeResult> {
@@ -91,7 +94,12 @@ export abstract class OrcaRuntimeWithResumeAgentSessionInWorkspace extends OrcaR
private async resumeClaimedAgentSession(
worktreeId: string,
session: ResumedAgentSession,
request: { captureHostId: ExecutionHostId; mutationId: string; signal?: AbortSignal },
request: {
captureHostId: ExecutionHostId
mutationId: string
launchConfig?: SleepingAgentLaunchConfig
signal?: AbortSignal
},
create: {
identity: { tabId: string; leafId: string }
onPtySpawnDispatched: () => void
@@ -145,7 +153,7 @@ export abstract class OrcaRuntimeWithResumeAgentSessionInWorkspace extends OrcaR
try {
resume = this.resolveMobileSessionResumeCommand(workspace, {
...session,
launchConfig: record?.launchConfig
launchConfig: request.launchConfig ?? record?.launchConfig
})
} catch (error) {
if (error instanceof WslHostWindowsOnlyAgentError) {
@@ -270,7 +270,8 @@ export function projectRuntimeMobileSessionTabs(
)
const { projectedTurnCompletedAt, ...clientAgentStatus } = frameAgentStatus(
projectedAgentStatus.agentStatus,
snapshot.worktree
snapshot.worktree,
terminalPty
)
const rawTurnCompletedAt =
hookAgentStatus?.live?.payload.turnCompletedAt ??
@@ -6,6 +6,7 @@ import type {
import type { TerminalHandleRecord, PtyIncarnationHandleRecord } from './terminal-handle-records'
import { TerminalIncarnationCandidates } from './terminal-incarnation-candidates'
import { retireReplacedLaunch } from '../launch/launch-evidence'
type Mutable<T> = { -readonly [K in keyof T]: T[K] }
/** Canonical terminal facts; semantic operations retain selection, callbacks and failure policy. */
@@ -82,6 +83,7 @@ export class TerminalIdentitySource {
}
setPtyIncarnationId(record: RuntimePtyWorktreeRecord, value: string | null): void {
retireReplacedLaunch(record, value)
this.setPtyField(record, 'incarnationId', value)
}
@@ -0,0 +1,21 @@
import { describe, expect, it } from 'vitest'
import { heldLaunchConfig, type PtyLaunchFacts } from './launch-evidence'
const config = { agentArgs: '--dangerously-skip-permissions', agentEnv: { FOO: '1' } }
function heldAs(agent: 'claude' | 'claude-agent-teams'): PtyLaunchFacts {
return {
incarnationId: 'p1',
launchEvidence: { kind: 'held', incarnationId: 'p1', agent, token: 'token', config }
}
}
describe('heldLaunchConfig', () => {
it('keeps a Claude agent teams launch note when its hook reports claude', () => {
expect(heldLaunchConfig(heldAs('claude-agent-teams'), 'claude')).toEqual(config)
})
it('gives a different agent typed into the pane no note', () => {
expect(heldLaunchConfig(heldAs('claude'), 'codex')).toBeUndefined()
})
})
@@ -0,0 +1,118 @@
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import { sameAgentIdentity } from '../../../../shared/agent-status/title/agent-title-owner'
import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation'
import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol'
/** Main's word on whether a PTY's process still runs an Orca launch. Always replaced whole, so its
* identity fences an async check; never persisted, so a main restart starts unknown. */
export type LaunchEvidence =
| { readonly kind: 'unknown' }
| { readonly kind: 'gone'; readonly incarnationId: PtyIncarnationId | null }
| {
readonly kind: 'held'
readonly incarnationId: PtyIncarnationId | null
readonly agent: TuiAgent
readonly token: string
readonly config: SleepingAgentLaunchConfig
}
export type PtyLaunchFacts = {
incarnationId: PtyIncarnationId | null
launchEvidence?: LaunchEvidence
launchConfig?: SleepingAgentLaunchConfig | null
}
type HeldLaunch = { agent: TuiAgent; token: string; config: SleepingAgentLaunchConfig }
/** The recipe of the Orca launch running in this PTY's process as `agent`; a typed agent gets none.
* A wrapper launch (Claude agent teams) reports its wrapped agent, which is still that launch. */
export function heldLaunchConfig(
pty: PtyLaunchFacts | null | undefined,
agent: string | null | undefined
): SleepingAgentLaunchConfig | undefined {
const evidence = pty?.launchEvidence
return evidence?.kind === 'held' &&
// A launch recorded before its process id was known belongs to the process until a replacement.
(evidence.incarnationId === null || evidence.incarnationId === pty?.incarnationId) &&
agent &&
sameAgentIdentity(evidence.agent, agent)
? evidence.config
: undefined
}
/** Main's word on this PTY's launch as `agent`: its recipe, null when none runs, undefined when main
* can't tell, so readers keep their earlier rule. */
export function launchStatement(
pty: PtyLaunchFacts | null | undefined,
agent: string | null | undefined
): SleepingAgentLaunchConfig | null | undefined {
const kind = pty?.launchEvidence?.kind ?? 'unknown'
return kind === 'unknown' ? undefined : (heldLaunchConfig(pty, agent) ?? null)
}
export function holdLaunch(
pty: PtyLaunchFacts,
incarnationId: PtyIncarnationId | null,
launch: HeldLaunch
): void {
pty.launchEvidence = { kind: 'held', incarnationId, ...launch }
}
/** A freshly started process: its own launch is held, and any other process runs none. */
export function recordFreshLaunch(pty: PtyLaunchFacts, launch: Partial<HeldLaunch> = {}): void {
const { agent, token, config } = launch
pty.launchEvidence =
agent && token && config
? { kind: 'held', incarnationId: pty.incarnationId, agent, token, config }
: { kind: 'gone', incarnationId: pty.incarnationId }
}
/** A finished command or confirmed exit; sticky for this process until a fresh launch. */
export function retireLaunch(
pty: PtyLaunchFacts,
incarnationId: PtyIncarnationId | null = pty.incarnationId
): void {
pty.launchEvidence = { kind: 'gone', incarnationId }
pty.launchConfig = null
}
/** Learning the first id of the same process binds its evidence; a new process can't still run its
* predecessor's launch, and the newcomer establishes its own. */
export function retireReplacedLaunch(pty: PtyLaunchFacts, next: PtyIncarnationId | null): void {
const previous = pty.incarnationId
const evidence = pty.launchEvidence
if (!evidence || !next || previous === next) {
return
}
if (!previous) {
if (evidence.kind !== 'unknown' && evidence.incarnationId === null) {
pty.launchEvidence = { ...evidence, incarnationId: next }
}
return
}
if (evidence.kind === 'unknown' || evidence.incarnationId !== next) {
retireLaunch(pty, previous)
}
}
/** A reattach to process `incarnationId` can't revive or replace what main proved about it. Else a
* retired note proves the launch gone; anything else is unknown, returned when a foreground check
* of the note may settle it. */
export function recordReattachedLaunch(
pty: PtyLaunchFacts,
incarnationId: PtyIncarnationId | undefined,
note: DaemonLaunchNote | null | undefined
): LaunchEvidence | null {
const current = pty.launchEvidence
if (current && current.kind !== 'unknown' && current.incarnationId === (incarnationId ?? null)) {
return null
}
if (note === null && incarnationId) {
retireLaunch(pty, incarnationId)
return null
}
const pending: LaunchEvidence = { kind: 'unknown' }
pty.launchEvidence = pending
return note && incarnationId ? pending : null
}
@@ -181,7 +181,12 @@ export abstract class OrcaRuntimeWithCreateRuntimeOwnedMobileSessionTerminal ext
}
if (recipe) {
livePty.pty.launchAgent ??= recipe.launchAgent ?? null
if (!livePty.pty.launchConfig && recipe.launchConfig) {
// A finished launch's recipe must not return to the shell left behind.
if (
!livePty.pty.launchConfig &&
recipe.launchConfig &&
livePty.pty.launchEvidence?.kind !== 'gone'
) {
livePty.pty.launchConfig = copySleepingAgentLaunchConfig(recipe.launchConfig)
}
}
@@ -11,7 +11,7 @@ import {
import { isTuiAgentEnabled } from '../../../../shared/agent-launch/catalog/tui-agent-selection'
import { buildAgentResumeStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-resume-startup'
import { buildAgentStartupPlan } from '../../../../shared/agent-launch/startup/tui-agent-startup'
import { resolveResumeLaunchRecipe } from '../../../../shared/agent-launch/choices/tui-agent-launch-defaults'
import { resolveResumeLaunchRecipe } from '../../../../shared/agent-launch/choices/resume-launch-recipe'
import { resolveAgentStartupPlanInputs } from '../../../../shared/agent-launch/startup/agent-startup-plan-inputs'
import {
resolveWslHostAgentLaunchInputs,
@@ -91,7 +91,7 @@ export abstract class OrcaRuntimeWithResolveMobileSessionTerminalCommand extends
agent: record.agent,
providerSession,
cmdOverrides: settings.agentCmdOverrides ?? {},
...resolveResumeLaunchRecipe(launchConfig),
...resolveResumeLaunchRecipe(launchConfig, record.agent, providerSession),
platform: launchRuntime.platform,
shell: agentLaunchQuotingShell(launchRuntime),
isRemote: Boolean(workspace.connectionId),
@@ -243,8 +243,8 @@ export abstract class OrcaRuntimeWithCreateTerminal extends OrcaRuntimeWithTermi
this.setPtyManagementTitleFromObservedTitle(pty, title, at)
)
}
this.watchLaunchComposer(
result.id,
this.watchLaunchedAgent(
pty,
recordTerminalLaunchMetadata(pty, result, launch, launchOpts.command)
)
if (!launch.adoptedStablePane) {
@@ -4,6 +4,7 @@ import type { RuntimePtyController } from '../lifecycle/runtime-pty-controller-c
import type { TerminalCreateOptions } from './terminal-create-options'
import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records'
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import { recordFreshLaunch } from './launch-evidence'
import {
copySleepingAgentLaunchConfig,
resolveLaunchCommandPaneAgent,
@@ -54,8 +55,8 @@ export function recordTerminalLaunchMetadata(
command: string | undefined
): TuiAgent | null {
if (launch.adoptedStablePane) {
// A lower owner can supply facts before this runtime has a launch record.
if (!pty.launchConfig && result.launchConfig) {
// A lower owner can supply facts before this runtime has a launch record, unless its launch ended.
if (!pty.launchConfig && result.launchConfig && pty.launchEvidence?.kind !== 'gone') {
pty.launchConfig = copySleepingAgentLaunchConfig(result.launchConfig)
}
pty.launchToken ??= result.launchToken ?? null
@@ -69,6 +70,11 @@ export function recordTerminalLaunchMetadata(
pty.launchToken = launch.launchToken ?? null
pty.launchIncarnationId = launch.launchToken ? pty.incarnationId : null
pty.launchAgent = launch.launchAgent ?? null
recordFreshLaunch(pty, {
agent: pty.launchAgent ?? undefined,
token: pty.launchToken ?? undefined,
config: pty.launchConfig ?? undefined
})
if (result.agentResumeRefused) {
pty.launchCommandAgent = null
return null
@@ -14,6 +14,7 @@ import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layo
import { randomUUID } from 'node:crypto'
import { paneStartFailure } from '../surface/pane-start-statuses'
import { collectLeafIds } from '../../../../shared/workspace-layout/terminal-pane-layout-tree'
import { recordFreshLaunch } from './launch-evidence'
export type SplitPaneSource = { worktreeId: string; tabId: string; leafId: string }
@@ -138,6 +139,9 @@ export abstract class OrcaRuntimeWithSplitPaneInMain extends OrcaRuntimeWithSpli
if (!createdPty) {
throw new Error('terminal_exited')
}
if (!result.isReattach) {
recordFreshLaunch(createdPty)
}
recordPtySurface(
this.terminalIdentity,
createdPty,
@@ -14,6 +14,7 @@ import type { Worktree } from '../../../../shared/worktree/types'
import { spawnInAdmittedPane, withdrawRuntimePane } from './runtime-pane-admission'
import { UNMEASURED_PTY_SIZE } from '../../../ipc/pty/pty-first-size'
import { resolveLaunchCommandPaneAgent } from './runtime-agent-launch-resolution'
import { recordFreshLaunch } from './launch-evidence'
// Rejected splits need only a quick teardown verdict before fallback kill; unreachable hosts must not stall rejection.
const REJECTED_SPLIT_PTY_STOP_TIMEOUT_MS = 2_000
@@ -129,6 +130,9 @@ export abstract class OrcaRuntimeWithSplitPtyBackedTerminal extends OrcaRuntimeW
)
createdPty.runtimeSessionOwned = pty.runtimeSessionOwned
createdPty.launchCommandAgent = resolveLaunchCommandPaneAgent(opts.command)
if (!result.isReattach) {
recordFreshLaunch(createdPty)
}
this.watchLaunchComposer(result.id, createdPty.launchCommandAgent)
this.setPairedRendererSessionOwnership(
createdPty.ptyId,
@@ -0,0 +1,90 @@
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation'
import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol'
import type { LaunchedAgentForeground } from '../wait/launched-agent-foreground'
import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records'
import {
holdLaunch,
recordReattachedLaunch,
retireLaunch,
type LaunchEvidence
} from '../launch/launch-evidence'
import { OrcaRuntimeWithInvalidateAllHandlesForPty } from './pty-handle-invalidation'
/** Main's admitted launch, kept in the daemon so a reattach after a main restart can re-arm it. */
export abstract class OrcaRuntimeWithDaemonLaunchNote extends OrcaRuntimeWithInvalidateAllHandlesForPty {
abstract readLaunchedAgentForeground(
ptyId: string,
agent: TuiAgent
): Promise<LaunchedAgentForeground>
protected abstract watchLaunchComposer(ptyId: string, agent: TuiAgent | null): void
/** Watch a launched agent's composer and keep its launch in the daemon. */
protected watchLaunchedAgent(pty: RuntimePtyWorktreeRecord, agent: TuiAgent | null): void {
this.watchLaunchComposer(pty.ptyId, agent)
this.armDaemonLaunchNote(pty)
}
/** Keep main's held launch in the daemon, which outlives main. */
protected armDaemonLaunchNote(pty: RuntimePtyWorktreeRecord): void {
const evidence = pty.launchEvidence
if (evidence?.kind === 'held') {
this.ptyController?.setLaunchNote?.(pty.ptyId, {
arm: { launchToken: evidence.token, launchConfig: evidence.config }
})
}
}
/** A finished command or confirmed exit; the daemon outlives main, so a reattach must not re-arm it. */
protected retireHeldLaunch(ptyId: string): RuntimePtyWorktreeRecord | undefined {
const pty = this.ptysById.get(ptyId)
if (pty?.launchEvidence?.kind === 'held') {
this.ptyController?.setLaunchNote?.(ptyId, { retire: pty.launchEvidence.token })
}
if (pty) {
retireLaunch(pty)
}
return pty
}
/** An unretired note is held only while its agent still holds the foreground. Main can't tell when
* the host keeps no notes (an older daemon) or the foreground is unreadable (Windows). */
protected recordReattachedLaunch(
pty: RuntimePtyWorktreeRecord,
incarnationId: PtyIncarnationId | undefined,
note: DaemonLaunchNote | null | undefined,
agent: TuiAgent | undefined
): void {
const pending = recordReattachedLaunch(pty, incarnationId, note)
if (pending && note && incarnationId && agent) {
void this.checkReattachedLaunch(pty, pending, incarnationId, note, agent)
}
}
private async checkReattachedLaunch(
pty: RuntimePtyWorktreeRecord,
pending: LaunchEvidence,
incarnationId: PtyIncarnationId,
note: DaemonLaunchNote,
agent: TuiAgent
): Promise<void> {
const foreground = await this.readLaunchedAgentForeground(pty.ptyId, agent).catch(
() => 'unknown' as const
)
// Newer evidence (a later attach, a finished command, a fresh launch) outranks this read.
if (
pty.launchEvidence !== pending ||
this.ptysById.get(pty.ptyId) !== pty ||
pty.incarnationId !== incarnationId
) {
return
}
if (foreground === 'shell') {
this.ptyController?.setLaunchNote?.(pty.ptyId, { retire: note.launchToken })
retireLaunch(pty)
} else if (foreground === 'agent' && pty.launchAgent === agent) {
holdLaunch(pty, incarnationId, { agent, token: note.launchToken, config: note.launchConfig })
}
}
}
@@ -3,9 +3,12 @@ import {
terminalExitError
} from '../../../../shared/terminal/pty/lifecycle/terminal-start-failure'
import type { PtySpawnResult } from '../../../providers/pty-spawn-result'
import { OrcaRuntimeWithInvalidateAllHandlesForPty } from './pty-handle-invalidation'
import type { PtyIncarnationId } from '../../../../shared/terminal/pty/lifecycle/pty-incarnation'
import type { TuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent'
import type { SleepingAgentLaunchConfig } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import { recordFreshLaunch, retireLaunch } from '../launch/launch-evidence'
import type { DaemonLaunchNote } from '../../../daemon/protocol/daemon-launch-note-protocol'
import { OrcaRuntimeWithDaemonLaunchNote } from './daemon-launch-note'
import { isValidTerminalTabId } from '../../../../shared/workspace-layout/terminal-tab-id'
import { isTerminalLeafId, makePaneKey } from '../../../../shared/workspace-layout/stable-pane-id'
import { isTuiAgent } from '../../../../shared/agent-launch/catalog/tui-agent-config'
@@ -20,7 +23,7 @@ import { ORCA_LAYOUT_OWNER_IS_MAIN } from '../../../../shared/layout-owner-switc
import { mainTerminalRegistered } from '../surface/main-terminal-surfaces'
import { assertPaneBoundAtRegistration, isRuntimeHostedWorkspace } from './bind-first-registration'
export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalidateAllHandlesForPty {
export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithDaemonLaunchNote {
protected abstract ensurePtyBackedMobileSurfaceForRendererTab(
worktreeId: string,
tabId: string
@@ -42,13 +45,21 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida
incarnationId?: PtyIncarnationId
/** Handle allocated for the replacement incarnation, when one is known. */
terminalHandle?: string
agentLaunchAuthority?: { launchToken: string; launchAgent: TuiAgent }
agentLaunchAuthority?: {
launchToken: string
launchAgent: TuiAgent
launchConfig?: SleepingAgentLaunchConfig
}
/** The agent a fresh spawn's launch command starts, whose submits wait for its composer. */
launchedAgent?: TuiAgent
providerReattachLaunchIdentity?: {
incarnationId: PtyIncarnationId
launchAgent: TuiAgent
}
/** A newly started process, which runs no launch but an admitted one. */
freshSpawn?: true
/** A reattach, with its host's launch note; none when the host keeps no notes (an older daemon, SSH). */
reattach?: { launchNote?: DaemonLaunchNote | null }
},
isWsl?: boolean
): void {
@@ -153,9 +164,18 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida
pty.launchToken = agentLaunchAuthority.launchToken
pty.launchIncarnationId = binding.incarnationId
pty.launchAgent = agentLaunchAuthority.launchAgent
recordFreshLaunch(pty, {
agent: agentLaunchAuthority.launchAgent,
token: agentLaunchAuthority.launchToken,
config: agentLaunchAuthority.launchConfig
})
this.armDaemonLaunchNote(pty)
} else if (binding?.freshSpawn && pty.incarnationId === (binding.incarnationId ?? null)) {
retireLaunch(pty)
}
this.watchLaunchComposer(ptyId, binding?.launchedAgent ?? null)
const providerReattachLaunchIdentity = binding?.providerReattachLaunchIdentity
let reattachedAgent: TuiAgent | undefined
if (
providerReattachLaunchIdentity &&
paneKey &&
@@ -165,7 +185,12 @@ export abstract class OrcaRuntimeWithRegisterPty extends OrcaRuntimeWithInvalida
isTuiAgent(providerReattachLaunchIdentity.launchAgent)
) {
// Why: daemon metadata owns the surviving process; its incarnation fence restores identity without minting renderer launch authority.
pty.launchAgent = providerReattachLaunchIdentity.launchAgent
pty.launchAgent = reattachedAgent = providerReattachLaunchIdentity.launchAgent
}
// An older relay reports no incarnation; that still can't prove the launch gone.
if (binding?.reattach && (pty.incarnationId ?? undefined) === binding.incarnationId) {
const { launchNote } = binding.reattach
this.recordReattachedLaunch(pty, binding.incarnationId, launchNote, reattachedAgent)
}
const pendingIncarnation = this.pendingPtyRegistrationIncarnations.get(ptyId)?.incarnationId
if (
@@ -1,3 +1,4 @@
import type { DaemonLaunchNoteChange } from '../../../daemon/protocol/daemon-launch-note-protocol'
import type {
TerminalLimitStatus,
TerminalLimitUpdate
@@ -172,6 +173,7 @@ export type RuntimePtyController = {
supportsForegroundObservation?(ptyId: string): boolean
confirmForegroundProcess?(ptyId: string): Promise<string | null>
confirmShellForeground?(ptyId: string): Promise<boolean>
setLaunchNote?(ptyId: string, change: DaemonLaunchNoteChange): void
hasChildProcesses?(ptyId: string): Promise<boolean>
clearBuffer?(ptyId: string): Promise<void>
resetInputModes?(ptyId: string): Promise<void>
@@ -183,7 +183,7 @@ export abstract class OrcaRuntimeWithGetOrchestrationDispatchAuthority extends O
}
protected retirePtyAgentLaunchAuthority(ptyId: string): void {
const pty = this.ptysById.get(ptyId)
const pty = this.retireHeldLaunch(ptyId)
if (!pty) {
return
}
@@ -18,6 +18,7 @@ import type { RetainedTailRedrawCursor } from '../output/tail/terminal-tail-redr
import type { TerminalTailWaitState } from '../wait/terminal-wait-tail-state'
import type { TerminalCommandPaint } from '../input/terminal-command-paint'
import type { PtyShellOwnershipMirror } from '../query/pty-shell-ownership-mirror'
import type { LaunchEvidence } from '../launch/launch-evidence'
import type { TerminalExitCause } from '../../../../shared/terminal/pty/lifecycle/terminal-exit-cause'
import type { AgentSessionOwnerBinding } from '../../../../shared/agent-session/agent-session-host-authority'
@@ -92,6 +93,8 @@ export type RuntimePtyWorktreeRecord = RuntimeTerminalTailState & {
launchToken: string | null
launchIncarnationId: PtyIncarnationId | null
launchAgent: TuiAgent | null
/** Whether the process still runs an Orca launch; missing when main can't tell. */
launchEvidence?: LaunchEvidence
/** Identify flagged unmanaged --command panes before foreground reads; null for adopted/restored panes. */
launchCommandAgent: TuiAgent | null
agentSessionOwners: AgentSessionOwnerBinding[]
@@ -9,6 +9,7 @@ import {
type ResumeRecordTab
} from '../../../../shared/agent-session/lifecycle/agent-resume-record-from-status'
import {
isPaneSleepRecord,
normalizeAgentProviderSession,
type SleepingAgentLaunchConfig,
type SleepingAgentSessionRecord
@@ -22,11 +23,38 @@ import type { WorkspaceSessionState } from '../../../../shared/workspace-session
/** The part of a pane's previous status the next one may inherit its provider session from. */
export type PreviousHookStatus = Pick<ResumeRecordStatus, 'agentType' | 'state' | 'providerSession'>
/** A pane's agent launch recipe, when its terminal was launched as `agent`. */
/** Main's word on a pane's launch as `agent`: its note, null for none, undefined when main can't tell. */
export type PaneLaunchConfigOf = (
paneKey: string,
agent: ResumeRecordStatus['agentType']
) => SleepingAgentLaunchConfig | undefined
) => SleepingAgentLaunchConfig | null | undefined
/** Main's word on the launch, else the pane's earlier record of this session when main can't tell. */
function statusLaunchConfig(
statement: SleepingAgentLaunchConfig | null | undefined,
existing: SleepingAgentSessionRecord | undefined,
status: ResumeRecordStatus,
keepsEarlier = true
): SleepingAgentLaunchConfig | undefined {
return statement === undefined && keepsEarlier
? recordLaunchConfigForStatus(existing, status)
: (statement ?? undefined)
}
/** A sleep's snapshot of this session waits for its wake; a status from no Orca launch neither
* replaces it nor inherits its recipe. */
function keepsSleepSnapshot(
statement: SleepingAgentLaunchConfig | null | undefined,
existing: SleepingAgentSessionRecord | undefined,
status: ResumeRecordStatus
): boolean {
return (
statement === null &&
existing !== undefined &&
isPaneSleepRecord(existing) &&
recordLaunchConfigForStatus(existing, status) !== undefined
)
}
/** A hook row as the window's status entry reads it; null for rows that are not a pane's status. */
export function resumeStatusFromHookRow(
@@ -80,17 +108,22 @@ export function hookStatusResumeCommand(args: {
}
const existing = session.sleepingAgentSessionsByPaneKey?.[status.paneKey]
const retainsResumableIdentity = statusRetainsResumableIdentity(status, status.providerSession)
const statement = args.launchConfigOf(status.paneKey, status.agentType)
if (keepsSleepSnapshot(statement, existing, status)) {
return null
}
const live = liveResumeRecord({
entry: status,
retainsResumableIdentity,
worktreeIdOf: () => worktreeId,
tabOf: () => tab,
capturedAt: status.updatedAt,
launchConfig:
args.launchConfigOf(status.paneKey, status.agentType) ??
(status.state !== 'done' || retainsResumableIdentity
? recordLaunchConfigForStatus(existing, status)
: undefined)
launchConfig: statusLaunchConfig(
statement,
existing,
status,
status.state !== 'done' || retainsResumableIdentity
)
})
const change = liveResumeRecordChange(existing, live)
if (!change) {
@@ -112,6 +145,10 @@ export function quitResumeRecords(args: {
}): SleepingAgentSessionRecord[] {
return args.statuses.flatMap((status) => {
const existing = args.session.sleepingAgentSessionsByPaneKey?.[status.paneKey]
const statement = args.launchConfigOf(status.paneKey, status.agentType)
if (keepsSleepSnapshot(statement, existing, status)) {
return []
}
const tabFor = tabOf(args.session, status.paneKey)
const record = capturedResumeRecord({
entry: status,
@@ -120,9 +157,7 @@ export function quitResumeRecords(args: {
capturedAt: args.capturedAt,
worktreeIdOf: () => status.worktreeId ?? args.worktreeIdOf(status.paneKey),
tabOf: tabFor,
launchConfigOf: () =>
args.launchConfigOf(status.paneKey, status.agentType) ??
recordLaunchConfigForStatus(existing, status)
launchConfigOf: () => statusLaunchConfig(statement, existing, status)
})
// Only a pane this partition holds keeps a record here.
return record && tabFor(record.worktreeId) ? [record] : []
@@ -0,0 +1,115 @@
// A pane's saved recipe follows main's word on its launch, not the session the agent names.
import { describe, expect, it, vi } from 'vitest'
import type { AgentStatusIpcPayload } from '../../../../shared/agent-status/contracts/agent-status-ipc-payload'
import type { SleepingAgentSessionRecord } from '../../../../shared/agent-session/lifecycle/agent-session-resume'
import type { ExecutionHostId } from '../../../../shared/execution-host'
import type { LayoutApplyOutcome } from '../../../../shared/workspace-layout/workspace-layout-command-types'
import { applyCommandToSession } from '../../../persistence/terminal-topology/terminal-pane-admission'
vi.mock('../../../../shared/layout-owner-switch', () => ({ ORCA_LAYOUT_OWNER_IS_MAIN: true }))
// Preserve side-effect order: mocks, lifecycle, fixtures.
await import('../../orca-runtime-tests/runtime-test-module-registration.spec')
const { OrcaRuntimeService } = await import('../../orca-runtime')
await import('../../orca-runtime-tests/orca-runtime-test-lifecycle.spec')
const {
HEADLESS_LEAF_ID,
TEST_WORKTREE_ID,
makeRuntimeStoreWithWorkspaceSession,
makeWorkspaceSessionWithHeadlessTerminal
} = await import('../../orca-runtime-tests/orca-runtime-test-fixtures.spec')
const PANE_KEY = `host-tab:${HEADLESS_LEAF_ID}`
const PTY_ID = 'persisted-pty'
const SESSION = { key: 'session_id' as const, id: 'claude-session-1' }
const RECIPE = { agentArgs: '--dangerously-skip-permissions', agentEnv: {} }
function savedRecord(origin: SleepingAgentSessionRecord['origin']): SleepingAgentSessionRecord {
return {
paneKey: PANE_KEY,
tabId: 'host-tab',
worktreeId: TEST_WORKTREE_ID,
agent: 'claude',
providerSession: SESSION,
prompt: '',
state: 'done',
capturedAt: 5,
updatedAt: 5,
origin,
connectionId: null,
launchConfig: RECIPE
}
}
function claudeRow(): AgentStatusIpcPayload {
return {
paneKey: PANE_KEY,
worktreeId: TEST_WORKTREE_ID,
agentType: 'claude',
providerSession: SESSION,
state: 'working',
prompt: 'keep going',
receivedAt: 10,
stateStartedAt: 10,
connectionId: null
}
}
function makeRuntime(saved: SleepingAgentSessionRecord) {
const { runtimeStore, getSession, setSession } = makeRuntimeStoreWithWorkspaceSession(
makeWorkspaceSessionWithHeadlessTerminal({
sleepingAgentSessionsByPaneKey: { [PANE_KEY]: saved }
})
)
const applyLayoutCommand = vi.fn(
async (
command: Parameters<typeof applyCommandToSession>[2],
hostIds: ExecutionHostId[]
): Promise<LayoutApplyOutcome> => {
for (const hostId of hostIds) {
const change = applyCommandToSession(hostId, getSession(), command)
if (change.session) {
setSession(change.session)
}
}
return { ok: true, result: {} }
}
)
const runtime = new OrcaRuntimeService(Object.assign(runtimeStore, { applyLayoutCommand }))
runtime.syncWindowGraph(0, { tabs: [], leaves: [] })
const binding = { tabId: 'host-tab', leafId: HEADLESS_LEAF_ID, incarnationId: 'p1' }
return {
runtime,
binding,
getSession,
savedAfterStatus: async () => {
runtime.recordHookStatusResume(claudeRow())
await runtime['hookStatusResumeWrites']
return getSession().sleepingAgentSessionsByPaneKey?.[PANE_KEY]
}
}
}
describe('a pane saved recipe and the launch running in it', () => {
it('gives an agent typed into a fresh shell none of the session earlier recipe', async () => {
const { runtime, binding, savedAfterStatus } = makeRuntime(savedRecord('live'))
runtime.registerPty(PTY_ID, TEST_WORKTREE_ID, null, { ...binding, freshSpawn: true })
const saved = await savedAfterStatus()
expect(saved?.state).toBe('working')
expect(saved?.launchConfig).toBeUndefined()
})
it('keeps a sleep snapshot for its wake without lending its recipe to a typed resume', async () => {
const { runtime, binding, getSession, savedAfterStatus } = makeRuntime(
savedRecord('worktree-sleep')
)
runtime.registerPty(PTY_ID, TEST_WORKTREE_ID, null, {
...binding,
agentLaunchAuthority: { launchToken: 'launch-1', launchAgent: 'claude', launchConfig: RECIPE }
})
runtime.emitDaemonPtyTransientFact(PTY_ID, { kind: 'command-finished', exitCode: 0 })
expect(await savedAfterStatus()).toEqual(savedRecord('worktree-sleep'))
Object.assign(runtime, { getAgentProviderSessionSnapshotFn: () => [claudeRow()] })
expect(runtime.quitResumeRecordsFor(getSession())).toEqual([])
})
})
@@ -1,5 +1,7 @@
import { sleepingRecordsEquivalentIgnoringCaptureTime } from '../../../../shared/agent-session/lifecycle/agent-resume-record-equivalence'
import { OrcaRuntimeWithStopTerminalsForWorktree } from './worktree-terminal-stop'
import { launchStatement } from '../launch/launch-evidence'
import type { RuntimePtyWorktreeRecord } from '../records/runtime-terminal-state-records'
import {
applyWorktreeSleepResumeRecords,
captureWorktreeSleepResumeRecords,
@@ -96,12 +98,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu
paneKeysByPtyId: new Map(
[...ptyIds].map((ptyId) => [ptyId, this.collectAgentStatusPaneKeysForPty(ptyId)])
),
launchByPtyId: new Map(
[...ptyIds].map((ptyId) => {
const pty = this.ptysById.get(ptyId)
return [ptyId, { agent: pty?.launchAgent ?? null, config: pty?.launchConfig ?? null }]
})
),
launchByPtyId: new Map([...ptyIds].map((ptyId) => [ptyId, this.ptysById.get(ptyId)])),
readRows: () => this.getAgentProviderSessionSnapshotFn?.() ?? [],
checkAgentPresence: this.checkHookAgentPresenceFn,
capturedAt: Date.now()
@@ -129,18 +126,11 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu
>()
private hookStatusResumeWrites: Promise<void> = Promise.resolve()
private readonly paneLaunchConfigOf: PaneLaunchConfigOf = (paneKey, agent) => {
for (const pty of this.ptysById.values()) {
if (
pty.launchConfig &&
pty.launchAgent === agent &&
this.paneOfPty(pty).paneKey === paneKey
) {
return pty.launchConfig
}
}
return undefined
}
protected abstract getPtyRecordForPaneKey(paneKey: string): RuntimePtyWorktreeRecord | null
/** Main's word on the Orca launch running in this pane now; the one check every saved note passes. */
getLaunchStatementForPaneKey: PaneLaunchConfigOf = (paneKey, agent) =>
launchStatement(this.getPtyRecordForPaneKey(paneKey), agent)
// Main records accepted status for its panes even without windows, preserving window resume rules; serialize writes so statuses read prior records.
recordHookStatusResume(row: AgentStatusIpcPayload): void {
@@ -207,7 +197,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu
status,
session: this.store.getWorkspaceSession(hostId),
worktreeId,
launchConfigOf: this.paneLaunchConfigOf
launchConfigOf: this.getLaunchStatementForPaneKey
})
if (command) {
// Not this.applyLayoutCommand: this runs inside the resume-record queue, which that would await.
@@ -225,7 +215,7 @@ export abstract class OrcaRuntimeWithWorktreeSleepResumeRecording extends OrcaRu
statuses,
session,
worktreeIdOf: (paneKey) => this.getTerminalWorktreeIdForPaneKey(paneKey),
launchConfigOf: this.paneLaunchConfigOf,
launchConfigOf: this.getLaunchStatementForPaneKey,
capturedAt: Date.now()
})
}

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