Files
orca/config/scripts/build-orcad-template.mjs
T
Jinwoo Hong 9b99928cb5 fix(layout): close the dark layout path's gaps, and refuse to package it (#29207)
* feat(layout): add the dark layout.apply channel and route pane splits through main behind ORCA_LAYOUT_OWNER

A build made with ORCA_LAYOUT_OWNER=main registers layout.apply: main applies the
window's layout command to the stored partition through the shared applyLayoutCommand,
minting new ids. A user split then waits for main's answer and mounts the pane id main
minted. Every other build substitutes 'window', so neither branch is compiled in.

* fix(layout): write only the records a layout.apply command touched

A load-then-save rewrite also normalizes records the command never touched. The command's
effect is now the diff between the save before and after it, written onto the stored
partition record by record. A split whose main reply says a paired server holds the tab
splits as today.

* fix(layout): write a load-supplied record whole and check that patched partitions reload to the command's result

* feat(layout): close, rename and equalize panes through main behind ORCA_LAYOUT_OWNER

In a layout-owner build the window's pane close, title change and equalize go through
layout.apply and the window shows main's answer. A window pane close keeps the legacy
close's rules: the tab's last pane is refused, a pane restarted since main read the close is
left alone, every partition holding the tab closes it, and the tab's remote session id follows
the remaining pane. The rules sit behind a command field only layout.apply sets.

* fix(layout): close the tab when a racing pane close leaves the window one pane

* fix(layout): leave an unmounted tab alone when main refuses its last pane

* feat(layout): move panes and save divider ratios through main behind ORCA_LAYOUT_OWNER

Claude-Session: 10569c9a-a0a1-4fc9-8469-0edfb7aed125

* test(layout): a taken pane drop whose pane closed does nothing

Claude-Session: 10569c9a-a0a1-4fc9-8469-0edfb7aed125

* test(layout): pin the window's pane move to main's saved tree, and the drops main cannot take

Claude-Session: 10569c9a-a0a1-4fc9-8469-0edfb7aed125

* fix(layout): close a user's pane even if its terminal restarted, as today

Claude-Session: 10569c9a-a0a1-4fc9-8469-0edfb7aed125

* test(layout): pin the restarted-pane close directly, not through a made-up profile state

Claude-Session: 10569c9a-a0a1-4fc9-8469-0edfb7aed125

* fix(layout): leave a split to today's path only when the workspace's row names a paired server

The split switch point asked which host to route to with a helper that falls back to the focused
server, so a focused server could claim a workspace whose row names no owner. Use the same owner
test the tab mirror uses.

* test(layout): type the split owner mock without a cast

* test(layout): type the layout-owner command mocks with the real signature

* test(layout): type the gesture command mock with the real signature

* fix(layout): close the dark path's gaps: unmounted split panes, refused or failed splits and moves, ratios during a move, release guard

- A pane main saved but the window could not mount (source pane or manager gone during the await)
  is closed again in main, so it does not come back on restart.
- A split main refuses because its copy lacks the workspace, tab or pane, or a failed call, splits
  as today; a refused or failed move moves as today.
- Divider ratios committed while a move is in flight wait for the window's move, then go to main.
- The orcad bundle gets the ORCA_LAYOUT_OWNER define when the switch is on.
- Packaging and the orcad template refuse ORCA_LAYOUT_OWNER=main and any output a dark build marked.
- workspace-layout-record-patch.ts: no non-null assertions; plain comment for the map depth.

* test(layout): count a split pane as mounted from the split mock's own results

* fix(layout): act as today whenever main lacks the target or the call throws, not just for splits

- sendPaneCommandToLayoutOwner runs asToday for workspace/tab/pane_not_found and a thrown call, so
  close, rename and equalize fall back like split and move; a handler that throws no longer runs the
  fallback too.
- A close main refuses as its last pane, while this window still has others, closes as today.
- A move whose local step throws still releases held divider ratios.
- Drop the orcad output marker: nothing read it; the template build refuses the switch itself.

* test(layout): plain names for the last-pane fallback test and the marker comment

* docs(layout): say plainly what an indeterminate write can leave behind

* fix(layout): finish the main merge with this branch's versions of the layout-owner files

* test(build): copy the layout-owner build guard into the compiler-cache checkout fixture

* fix: carry this branch's build-guard changes onto main's versions of three build files
2026-10-15 20:16:58 -07:00

230 lines
8.4 KiB
JavaScript

#!/usr/bin/env node
import { createHash } from 'node:crypto'
import {
chmodSync,
copyFileSync,
existsSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync
} from 'node:fs'
import { dirname, join, resolve } from 'node:path'
import {
ORCAD_NODE_PTY_DIR,
ORCAD_NODE_RUNTIME_MARKER_FILENAME,
ORCAD_SERVER_TARGET_FILENAME,
ORCAD_TEMPLATE_MANIFEST_FILENAME,
ORCAD_TEMPLATE_TARGETS_DIR,
orcadNodePtySlotFiles,
orcadTemplateCommonFilenames,
orcadTemplateTargetFilenames
} from '../../src/shared/orcad-artifacts.ts'
import { orcadAgentBrowserNativeName } from '../../src/shared/orcad-agent-browser-name.ts'
import {
COMPAT_SERVER_TARGET_BASES,
COMPAT_SERVER_TARGETS,
ORCAD_TEMPLATE_TARGETS,
pinnedNodeRuntimeAsset
} from '../../src/shared/node-runtime-pin.ts'
import { ORCAD_PREBUILDS_DIR } from './build-orcad-prebuilds.mjs'
import {
COMPAT_SLOT_ADDONS,
findCompatAddonGaps,
findSlotProblems,
readManifest
} from './orcad-prebuild-slot-contents.mjs'
import { runProcessSync } from '@orca/process-host'
import { verifyPackagedOrcadTemplate } from './verify-packaged-orcad-template.cjs'
import { assertNotLayoutOwnerBuild } from '../layout-owner-build.cjs'
const root = resolve(import.meta.dirname, '../..')
const outputDir = join(root, 'out', 'orcad-template')
const buildDir = join(root, 'out', '.orcad-template-build')
const commonArtifacts = orcadTemplateCommonFilenames()
function isExecutable(filename) {
return /(?:^|\/)(?:rg|spawn-helper)$/.test(filename)
}
function copy(source, destination, executable = false) {
mkdirSync(dirname(destination), { recursive: true })
copyFileSync(source, destination)
if (executable && process.platform !== 'win32') {
chmodSync(destination, 0o755)
}
}
function sha256(path) {
return createHash('sha256').update(readFileSync(path)).digest('hex')
}
/** One full package per target; each needs that target's node-pty slot in out/orcad-prebuilds. */
function buildTargetPackage(target) {
const packageDir = join(buildDir, target, 'orcad')
const result = runProcessSync({
program: process.execPath,
args: [
join(root, 'config/scripts/build-orcad-node.mjs'),
'--target',
target,
'--out-dir',
packageDir
],
cwd: root,
// Why no agent-browser: the template ships inside every desktop build (design D2), and seven
// ~10 MB browsers would outweigh everything else in it; a slot without one reports no browser.
env: { ...process.env, ORCAD_OMIT_AGENT_BROWSER: '1' },
stdio: 'inherit',
timeoutMs: null
})
if (result.code !== 0) {
throw new Error(`orcad ${target} package build failed with exit ${result.code ?? 'unknown'}`)
}
return packageDir
}
function stageTarget(target, packageDir) {
const destination = join(outputDir, ORCAD_TEMPLATE_TARGETS_DIR, target)
const files = {}
for (const filename of orcadTemplateTargetFilenames(target)) {
const staged = join(destination, ...filename.split('/'))
copy(join(packageDir, ...filename.split('/')), staged, isExecutable(filename))
files[filename] = sha256(staged)
}
const browserName = orcadAgentBrowserNativeName(
target.split('-')[0],
target.split('-')[1],
target.endsWith('-musl') ? 'musl' : 'glibc'
)
const browserSource = join(packageDir, browserName)
if (!existsSync(browserSource)) {
return { files }
}
const browserDestination = join(destination, browserName)
copy(browserSource, browserDestination, true)
return { files, browserName, browserSha256: sha256(browserDestination) }
}
/**
* `--targets a,b` builds a partial template for CI jobs that can fill only some prebuild slots
* (the SSH hostile-host matrix). A shipped template always carries every target.
*/
export function requestedTemplateTargets(argv = process.argv) {
const index = argv.indexOf('--targets')
if (index === -1) {
return ORCAD_TEMPLATE_TARGETS
}
const targets = (argv[index + 1] ?? '').split(',').filter(Boolean)
const unknown = targets.filter((target) => !ORCAD_TEMPLATE_TARGETS.includes(target))
if (targets.length === 0 || unknown.length > 0) {
throw new Error(
`--targets needs a comma-separated subset of ${ORCAD_TEMPLATE_TARGETS.join(',')}; got ${argv[index + 1] ?? 'nothing'}`
)
}
return [...new Set(targets)]
}
/**
* A compat target (design D6 rung B) is its base target's package with the compat slot's addons
* and runtime marker swapped in; everything else is target-independent or libc-static.
* Omitted, not failed, when this build has no compat slot: rung B then refuses as unavailable.
*/
function stageCompatTarget(compat, basePackageDir) {
const problems = findSlotProblems(readManifest(ORCAD_PREBUILDS_DIR), ORCAD_PREBUILDS_DIR, [
compat
])
if (problems.length > 0) {
process.stdout.write(
`[build-orcad-template] skipping compat target ${compat}: ${problems.join('; ')}\n`
)
return null
}
const destination = join(outputDir, ORCAD_TEMPLATE_TARGETS_DIR, compat)
const slotFiles = new Map([
...orcadNodePtySlotFiles(compat).map((file) => [
`${ORCAD_NODE_PTY_DIR}/build/Release/${file}`,
join(ORCAD_PREBUILDS_DIR, compat, ...file.split('/'))
]),
...Object.entries(COMPAT_SLOT_ADDONS).map(([file, shipped]) => [
shipped,
join(ORCAD_PREBUILDS_DIR, compat, ...file.split('/'))
])
])
// Why fatal: the base binary would pass every check here and fail only on a compat host.
const gaps = findCompatAddonGaps(orcadTemplateTargetFilenames(compat), slotFiles)
if (gaps.length > 0) {
throw new Error(`compat target ${compat} would ship base-target addons: ${gaps.join(', ')}`)
}
const files = {}
for (const filename of orcadTemplateTargetFilenames(compat)) {
const staged = join(destination, ...filename.split('/'))
if (filename === ORCAD_SERVER_TARGET_FILENAME) {
mkdirSync(dirname(staged), { recursive: true })
writeFileSync(staged, `${compat}\n`)
} else if (filename === ORCAD_NODE_RUNTIME_MARKER_FILENAME) {
mkdirSync(dirname(staged), { recursive: true })
writeFileSync(staged, `${pinnedNodeRuntimeAsset(compat).executableSha256}\n`)
} else {
const source = slotFiles.get(filename) ?? join(basePackageDir, ...filename.split('/'))
copy(source, staged, isExecutable(filename))
}
files[filename] = sha256(staged)
}
return { files }
}
function sameBytes(left, right) {
return sha256(left) === sha256(right)
}
async function main() {
// The template is what releases ship as the server; a dark build must never become one.
assertNotLayoutOwnerBuild([])
const templateTargets = requestedTemplateTargets()
rmSync(buildDir, { recursive: true, force: true })
const packages = Object.fromEntries(
templateTargets.map((target) => [target, buildTargetPackage(target)])
)
rmSync(outputDir, { recursive: true, force: true })
mkdirSync(outputDir, { recursive: true })
const [firstTarget] = templateTargets
for (const filename of commonArtifacts) {
const source = join(packages[firstTarget], ...filename.split('/'))
// Why check every target: the template keeps one copy, so a per-target difference would ship wrong bytes.
for (const target of templateTargets) {
if (!sameBytes(source, join(packages[target], ...filename.split('/')))) {
throw new Error(`${filename} differs between ${firstTarget} and ${target} packages`)
}
}
copy(source, join(outputDir, ...filename.split('/')), isExecutable(filename))
}
const targets = Object.fromEntries(
templateTargets.map((target) => [target, stageTarget(target, packages[target])])
)
// A partial CI template stages a compat target only beside its base target.
for (const compat of COMPAT_SERVER_TARGETS.filter((candidate) =>
templateTargets.includes(COMPAT_SERVER_TARGET_BASES[candidate])
)) {
const staged = stageCompatTarget(compat, packages[COMPAT_SERVER_TARGET_BASES[compat]])
if (staged) {
targets[compat] = staged
}
}
const commonSha256 = Object.fromEntries(
commonArtifacts.map((filename) => [filename, sha256(join(outputDir, filename))])
)
writeFileSync(
join(outputDir, ORCAD_TEMPLATE_MANIFEST_FILENAME),
`${JSON.stringify({ schemaVersion: 3, commonSha256, targets }, null, 2)}\n`
)
verifyPackagedOrcadTemplate(join(root, 'out'), templateTargets)
rmSync(buildDir, { recursive: true, force: true })
process.stdout.write(`[build-orcad-template] ok — ${Object.keys(targets).length} targets\n`)
}
if (process.argv[1]?.endsWith('build-orcad-template.mjs')) {
await main()
}