diff --git a/.github/actions/detect-changes/action.yml b/.github/actions/detect-changes/action.yml index 268b0aa103c82..b2ab85be5bca3 100644 --- a/.github/actions/detect-changes/action.yml +++ b/.github/actions/detect-changes/action.yml @@ -10,7 +10,7 @@ outputs: description: Run Python tests / ruff / ty / windows-footguns. value: ${{ steps.classify.outputs.python }} frontend: - description: Run the TypeScript typecheck matrix + desktop build. + description: Run the TypeScript testing matrix + desktop build. value: ${{ steps.classify.outputs.frontend }} docker_meta: description: Docker setup and meta files have changed. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ab60120165362..7840bfdc361b7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,11 +70,11 @@ jobs: with: event_name: ${{ needs.detect.outputs.event_name }} - typecheck: - name: TypeScript + js-tests: + name: JS & TS checks needs: detect if: needs.detect.outputs.frontend == 'true' - uses: ./.github/workflows/typecheck.yml + uses: ./.github/workflows/js-tests.yml docs-site: name: Docs Site @@ -139,7 +139,7 @@ jobs: needs: - tests - lint - - typecheck + - js-tests - docs-site - history-check - contributor-check @@ -154,14 +154,18 @@ jobs: steps: - name: Evaluate job results env: - RESULTS: ${{ toJSON(needs.*.result) }} + NEEDS: ${{ toJSON(needs) }} run: | - echo "$RESULTS" | python3 -c " + echo "$NEEDS" | python3 -c " import json, sys - results = json.load(sys.stdin) - failed = [r for r in results if r == 'failure'] + needs = json.load(sys.stdin) + failed = [name for name, info in needs.items() if info['result'] == 'failure'] + for name, info in sorted(needs.items()): + result = info['result'] + icon = '✅' if result in ('success', 'skipped') else '❌' + print(f'{icon} {name}: {result}') if failed: - print(f'::error::{len(failed)} job(s) failed') + print(f'::error::{len(failed)} job(s) failed: {\", \".join(failed)}') sys.exit(1) print('All checks passed (or were skipped)') " diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.yml new file mode 100644 index 0000000000000..db08947b270c0 --- /dev/null +++ b/.github/workflows/js-tests.yml @@ -0,0 +1,49 @@ +# .github/workflows/js-tests.yml +name: JS Tests + +on: + workflow_call: + +jobs: + workspaces: + name: List npm workspaces + runs-on: ubuntu-latest + outputs: + packages: ${{ steps.set-matrix.outputs.packages }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + cache: npm + - uses: ./.github/actions/retry + with: + command: npm ci --ignore-scripts + - id: set-matrix + run: | + PACKAGES=$(npm query .workspace | jq -c '[.[].location]') + if [ "$PACKAGES" = "[]" ] || [ -z "$PACKAGES" ]; then + echo "::error::Workspace discovery produced an empty package list — refusing to emit a zero-length matrix (would skip all JS/TS checks silently)." + exit 1 + fi + echo "packages=$PACKAGES" >> "$GITHUB_OUTPUT" + + check: + name: Typecheck & Test + runs-on: ubuntu-latest + needs: workspaces + strategy: + matrix: + package: ${{ fromJson(needs.workspaces.outputs.packages) }} + fail-fast: false # report all failures, not just the first one + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 + with: + node-version: 22 + cache: npm + - uses: ./.github/actions/retry + with: + # --ignore-scripts: TS & tests don't need native deps + command: npm ci --ignore-scripts + - run: npm run --prefix ${{ matrix.package }} check diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml deleted file mode 100644 index dd2906629b015..0000000000000 --- a/.github/workflows/typecheck.yml +++ /dev/null @@ -1,51 +0,0 @@ -# .github/workflows/typecheck.yml -name: Typecheck - -on: - workflow_call: - -jobs: - typecheck: - name: Check TypeScript - runs-on: ubuntu-latest - strategy: - matrix: - package: - [ui-tui, web, apps/bootstrap-installer, apps/desktop, apps/shared] - fail-fast: false # report all failures, not just the first one - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: 22 - cache: npm - # --ignore-scripts: typecheck only needs the TS sources + type defs, not - # native builds. Skipping install scripts drops node-pty's node-gyp - # header fetch — the transient flake that killed this job pre-`tsc` — and - # is faster. retry covers the remaining registry blips. - - uses: ./.github/actions/retry - with: - command: npm ci --ignore-scripts - - run: npm run --prefix ${{ matrix.package }} typecheck - - # Production build of the desktop renderer. `typecheck` runs `tsc` only, - # which does NOT exercise Vite/Rolldown module resolution — so an - # unresolvable package export (e.g. a transitive @assistant-ui/tap that no - # longer exports "./react-shim") slips past typecheck and only explodes when - # users build apps/desktop from source on install/update. Run the real - # `vite build` here so that class of break fails in CI instead. - desktop-build: - name: Build desktop app - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 - with: - node-version: 22 - cache: npm - # Keep install scripts here: the production build may need node-pty's - # native binary. retry handles the transient install-time fetch flakes. - - uses: ./.github/actions/retry - with: - command: npm ci - - run: npm run --prefix apps/desktop build diff --git a/.gitignore b/.gitignore index c48fcb3515a45..4d25e5425b6bc 100644 --- a/.gitignore +++ b/.gitignore @@ -69,7 +69,7 @@ hermes_cli/web_dist/ apps/desktop/build/ apps/desktop/dist/ apps/desktop/release/ -apps/desktop/*.tsbuildinfo +*.tsbuildinfo # Web UI assets — synced from @nous-research/ui at build time via # `npm run sync-assets` (see web/package.json). diff --git a/AGENTS.md b/AGENTS.md index a3d5e5be8413f..78a150ab0c350 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1354,3 +1354,58 @@ not the specific names. Reviewers should reject new change-detector tests; authors should convert them into invariants before re-requesting review. + +### Never read source code in tests + +A test that reads a source file's text is testing *the shape of the +source code*, not its behavior. This is a hard antipattern, banned outright. +Any test that reads a .py, .ts, .tsx, etc., file is suspect. + +**Why it's actively harmful, not just weak:** + +- It passes when the implementation is subtly broken (the regex matches a + call site that exists but is wired wrong) and fails when a correct + refactor changes formatting, variable names, or control flow with + identical runtime behavior. Both directions of failure are wrong. +- It can't be run against a built/bundled/minified artifact, so it silently + stops testing anything the moment code moves, gets renamed, or a + dependency reformats it. +- It actively blocks refactors: reviewers see "keeps a pattern intact" tests + fail during pure structural cleanup with no behavior change, and either + hand-wave the failure (dangerous) or waste time updating regexes that add + nothing (waste). +- It gives false confidence. a green suite full of source-regex tests + looks like coverage but has never once executed the code path it claims + to guard. + +**Do not write:** + +```ts +const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8') + +test('backend spawn hides the Windows console', () => { + assert.match(source, /spawn\(\s*backend\.command,\s*backend\.args[\s\S]{0,300}hiddenWindowsChildOptions/) +}) +``` + +**Do write — extract the logic into a small pure/DI-testable function and +call it for real:** + +```ts +// backend-spawn.ts +export function hiddenWindowsChildOptions(options: SpawnOptionsLike = {}, isWindows = process.platform === 'win32') { + if (!isWindows || 'windowsHide' in options) return options + return { ...options, windowsHide: true } +} + +// backend-spawn.test.ts +test('windowsHide defaults to true on Windows, is left alone elsewhere', () => { + assert.equal(hiddenWindowsChildOptions({}, true).windowsHide, true) + assert.equal(hiddenWindowsChildOptions({}, false).windowsHide, undefined) + assert.equal(hiddenWindowsChildOptions({ windowsHide: false }, true).windowsHide, false) +}) +``` + +If the logic lives inline in a god-file (`main.ts`, `cli.py`, +`gateway/run.py`) and extracting it feels disruptive: that's the actual +signal to do the extraction, not to regex around it. diff --git a/apps/bootstrap-installer/package.json b/apps/bootstrap-installer/package.json index 4638a8c905eab..7550e3c7c9891 100644 --- a/apps/bootstrap-installer/package.json +++ b/apps/bootstrap-installer/package.json @@ -12,7 +12,8 @@ "tauri:dev": "tauri dev", "tauri:build": "tauri build", "tauri:build:debug": "tauri build --debug", - "typecheck": "tsc -p . --noEmit" + "typecheck": "tsc -p . --noEmit", + "check": "npm run typecheck" }, "dependencies": { "@nous-research/ui": "0.16.0", diff --git a/apps/desktop/electron/backend-child.ts b/apps/desktop/electron/backend-child.ts new file mode 100644 index 0000000000000..fc44d49b0b40e --- /dev/null +++ b/apps/desktop/electron/backend-child.ts @@ -0,0 +1,55 @@ +/** + * backend-child.ts + * + * Windows-aware teardown for the desktop's managed backend child process. + * + * Node's `child.kill()` only signals the direct child. On Windows a backend + * that spawned its own grandchildren (a `hermes` REPL, a pty terminal + * session, the gateway) survives a plain SIGTERM and keeps files (e.g. the + * venv shim) locked. So on Windows we tree-kill via `forceKillProcessTree`; + * everywhere else a plain SIGTERM is correct and sufficient (POSIX has no + * mandatory locks, and the backend is not spawned detached so there's no + * process-group to negative-pid-kill). + * + * Extracted into its own dependency-free module (no electron import) so the + * SIGTERM-vs-tree-kill branching can be asserted directly with a fake child + * object and a spy `forceKillProcessTree`, instead of grepping main.ts source + * text for the function body. + */ + +export interface StopBackendChildDeps { + /** Defaults to the real platform check; injectable for tests. */ + isWindows?: boolean + /** Windows tree-kill implementation (real: taskkill /T /F via execFileSync). */ + forceKillProcessTree: (pid: number) => void +} + +export interface KillableChild { + pid?: number | null + killed?: boolean + kill: (signal: string) => void +} + +/** + * Stop a managed child process, choosing the right strategy for the platform. + * No-ops silently if `child` is falsy, already killed, or the kill attempt + * throws (the process may already be gone) -- mirrors the original inline + * best-effort semantics in main.ts. + */ +export function stopBackendChild(child: KillableChild | null | undefined, deps: StopBackendChildDeps) { + if (!child || child.killed) { + return + } + + const isWindows = deps.isWindows ?? process.platform === 'win32' + + try { + if (isWindows && Number.isInteger(child.pid)) { + deps.forceKillProcessTree(child.pid as number) + } else { + child.kill('SIGTERM') + } + } catch { + // Already gone. + } +} diff --git a/apps/desktop/electron/backend-command.test.ts b/apps/desktop/electron/backend-command.test.ts index 12531a693bbf3..2746ce78dafe4 100644 --- a/apps/desktop/electron/backend-command.test.ts +++ b/apps/desktop/electron/backend-command.test.ts @@ -1,7 +1,6 @@ -'use strict' - import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { dashboardFallbackArgs, serveBackendArgs, sourceDeclaresServe } from './backend-command' diff --git a/apps/desktop/electron/backend-command.ts b/apps/desktop/electron/backend-command.ts index 76ab03b089292..23cb87d4f785e 100644 --- a/apps/desktop/electron/backend-command.ts +++ b/apps/desktop/electron/backend-command.ts @@ -1,5 +1,3 @@ -'use strict' - // Backend subcommand routing for the desktop-managed Hermes process. // // The desktop app launches its own headless backend via `hermes serve` — it diff --git a/apps/desktop/electron/backend-env.test.ts b/apps/desktop/electron/backend-env.test.ts index 461697752623e..e24a66ee396ef 100644 --- a/apps/desktop/electron/backend-env.test.ts +++ b/apps/desktop/electron/backend-env.test.ts @@ -1,6 +1,7 @@ import assert from 'node:assert/strict' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { appendUniquePathEntries, diff --git a/apps/desktop/electron/backend-env.ts b/apps/desktop/electron/backend-env.ts index 506575618b4b3..a225e23817768 100644 --- a/apps/desktop/electron/backend-env.ts +++ b/apps/desktop/electron/backend-env.ts @@ -44,12 +44,14 @@ function appendUniquePathEntries(entries, { delimiter = path.delimiter } = {}) { if (!entry) { continue } + const parts = Array.isArray(entry) ? entry : String(entry).split(delimiter) for (const part of parts) { if (!part || seen.has(part)) { continue } + seen.add(part) ordered.push(part) } @@ -77,6 +79,7 @@ function normalizeHermesHomeRoot(hermesHome, { pathModule = pathModuleForPlatfor if (!hermesHome) { return hermesHome } + const resolved = pathModule.resolve(String(hermesHome)) const parent = pathModule.dirname(resolved) diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.ts index 1250d4a398364..43b39aafd862a 100644 --- a/apps/desktop/electron/backend-probes.test.ts +++ b/apps/desktop/electron/backend-probes.test.ts @@ -9,7 +9,8 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { canImportHermesCli, hermesRuntimeImportProbe, verifyHermesCli } from './backend-probes' diff --git a/apps/desktop/electron/backend-ready.test.ts b/apps/desktop/electron/backend-ready.test.ts index 40676f4c1eaae..eb090686241b9 100644 --- a/apps/desktop/electron/backend-ready.test.ts +++ b/apps/desktop/electron/backend-ready.test.ts @@ -16,7 +16,8 @@ import { EventEmitter } from 'node:events' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { DEFAULT_PORT_ANNOUNCE_TIMEOUT_MS, diff --git a/apps/desktop/electron/backend-ready.ts b/apps/desktop/electron/backend-ready.ts index 78f395c59eaf9..05b9b67351640 100644 --- a/apps/desktop/electron/backend-ready.ts +++ b/apps/desktop/electron/backend-ready.ts @@ -60,6 +60,7 @@ function waitForDashboardPort(child, timeoutMs = resolvePortAnnounceTimeoutMs()) if (done) { return } + done = true clearTimeout(timer) child.stdout.off('data', onData) @@ -130,12 +131,14 @@ function waitForDashboardReadyFile(readyFile, child, timeoutMs = resolvePortAnno if (done) { return } + done = true clearTimeout(timer) if (interval) { clearInterval(interval) } + child.off('exit', onExit) child.off('error', onError) } @@ -171,6 +174,7 @@ function waitForDashboardReadyFile(readyFile, child, timeoutMs = resolvePortAnno if (typeof interval.unref === 'function') { interval.unref() } + check() }) } diff --git a/apps/desktop/electron/bootstrap-platform.test.ts b/apps/desktop/electron/bootstrap-platform.test.ts index c4db7fd65b9cd..9ba60314e65f4 100644 --- a/apps/desktop/electron/bootstrap-platform.test.ts +++ b/apps/desktop/electron/bootstrap-platform.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { bundledRuntimeImportCheck, diff --git a/apps/desktop/electron/bootstrap-runner.test.ts b/apps/desktop/electron/bootstrap-runner.test.ts index 7ba50c85e74ff..eaffcac3ae082 100644 --- a/apps/desktop/electron/bootstrap-runner.test.ts +++ b/apps/desktop/electron/bootstrap-runner.test.ts @@ -2,7 +2,8 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { buildPinArgs, diff --git a/apps/desktop/electron/bootstrap-runner.ts b/apps/desktop/electron/bootstrap-runner.ts index 41ddd597a3791..284dcfeeb0b11 100644 --- a/apps/desktop/electron/bootstrap-runner.ts +++ b/apps/desktop/electron/bootstrap-runner.ts @@ -6,7 +6,7 @@ * the renderer. * * Wired from electron/main.ts: - * import { runBootstrap }from './bootstrap-runner.ts' + * import { runBootstrap }from './bootstrap-runner' * const result = await runBootstrap({ * installStamp, // INSTALL_STAMP from main.ts (may be null in dev) * activeRoot, // ACTIVE_HERMES_ROOT @@ -38,15 +38,9 @@ import fsp from 'node:fs/promises' import https from 'node:https' import path from 'node:path' -const IS_WINDOWS = process.platform === 'win32' - -function hiddenWindowsChildOptions(options = {}) { - if (!IS_WINDOWS || Object.prototype.hasOwnProperty.call(options, 'windowsHide')) { - return options - } +import { hiddenWindowsChildOptions } from './windows-child-options' - return { ...options, windowsHide: true } -} +const IS_WINDOWS = process.platform === 'win32' const STAMP_COMMIT_RE = /^[0-9a-f]{7,40}$/i @@ -73,6 +67,7 @@ function resolveLocalInstallScript(sourceRepoRoot) { if (!sourceRepoRoot) { return null } + const candidate = path.join(sourceRepoRoot, 'scripts', installScriptName()) try { @@ -96,6 +91,7 @@ function installedAgentInstallScript(hermesHome) { if (!hermesHome) { return null } + const candidate = path.join(hermesHome, 'hermes-agent', 'scripts', installScriptName()) try { @@ -425,6 +421,7 @@ function spawnPowerShell(scriptPath, args, { emit, stageName, abortSignal, herme if (abortSignal) { abortSignal.removeEventListener('abort', onAbort) } + reject(err) }) @@ -441,6 +438,7 @@ function spawnPowerShell(scriptPath, args, { emit, stageName, abortSignal, herme if (stderrBuf) { emit && emit({ type: 'log', stage: stageName, line: stderrBuf, stream: 'stderr' } as any) } + resolve({ stdout, stderr, code, signal, killed } as any) }) }) @@ -517,6 +515,7 @@ function spawnBash(scriptPath, args, { emit, stageName, abortSignal, hermesHome if (abortSignal) { abortSignal.removeEventListener('abort', onAbort) } + reject(err) }) @@ -532,6 +531,7 @@ function spawnBash(scriptPath, args, { emit, stageName, abortSignal, hermesHome if (stderrBuf) { emit && emit({ type: 'log', stage: stageName, line: stderrBuf, stream: 'stderr' }) } + resolve({ stdout, stderr, code, signal, killed }) }) }) diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts index 518d49805df84..e28f6959dab24 100644 --- a/apps/desktop/electron/connection-config.test.ts +++ b/apps/desktop/electron/connection-config.test.ts @@ -11,7 +11,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { AT_COOKIE_VARIANTS, diff --git a/apps/desktop/electron/dashboard-token.test.ts b/apps/desktop/electron/dashboard-token.test.ts index d07a7e3b111eb..e0a45eb36cc64 100644 --- a/apps/desktop/electron/dashboard-token.test.ts +++ b/apps/desktop/electron/dashboard-token.test.ts @@ -6,7 +6,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { adoptServedDashboardToken, diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.ts index 258db6c0f3c89..6d296ee1db910 100644 --- a/apps/desktop/electron/desktop-uninstall.test.ts +++ b/apps/desktop/electron/desktop-uninstall.test.ts @@ -10,7 +10,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { buildPosixCleanupScript, diff --git a/apps/desktop/electron/desktop-uninstall.ts b/apps/desktop/electron/desktop-uninstall.ts index feebe65951414..3d64486538234 100644 --- a/apps/desktop/electron/desktop-uninstall.ts +++ b/apps/desktop/electron/desktop-uninstall.ts @@ -106,6 +106,7 @@ function resolveRemovableAppPath(execPath, platform, env: any = {}) { if (env.APPIMAGE) { return env.APPIMAGE } + // Unpacked electron-builder tree: …/linux-unpacked/hermes const dir = p.dirname(exe) diff --git a/apps/desktop/electron/fs-read-dir.test.ts b/apps/desktop/electron/fs-read-dir.test.ts index 67adc624671bc..c77e60434ec13 100644 --- a/apps/desktop/electron/fs-read-dir.test.ts +++ b/apps/desktop/electron/fs-read-dir.test.ts @@ -2,9 +2,10 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' import { pathToFileURL } from 'node:url' +import { test } from 'vitest' + import { readDirForIpc } from './fs-read-dir' function mkTmpDir() { diff --git a/apps/desktop/electron/gateway-ws-probe.test.ts b/apps/desktop/electron/gateway-ws-probe.test.ts index f1e5ac941283c..222d3c699c169 100644 --- a/apps/desktop/electron/gateway-ws-probe.test.ts +++ b/apps/desktop/electron/gateway-ws-probe.test.ts @@ -10,7 +10,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { probeGatewayWebSocket } from './gateway-ws-probe' diff --git a/apps/desktop/electron/gateway-ws-probe.ts b/apps/desktop/electron/gateway-ws-probe.ts index 9ed1467141026..152e20b4d3227 100644 --- a/apps/desktop/electron/gateway-ws-probe.ts +++ b/apps/desktop/electron/gateway-ws-probe.ts @@ -80,6 +80,7 @@ function probeGatewayWebSocket( if (settled) { return } + settled = true clearTimers() @@ -107,6 +108,7 @@ function probeGatewayWebSocket( if (settled) { return } + opened = true // Upgrade accepted. Give the server a brief window to reject the // credential post-handshake (early close) before declaring success. @@ -189,6 +191,7 @@ function extractErrorReason(event) { if (event instanceof Error) { return event.message } + const err = event.error || event.message if (err instanceof Error) { diff --git a/apps/desktop/electron/git-review-ops.test.ts b/apps/desktop/electron/git-review-ops.test.ts index a88de4edf1290..a06fcdace39fc 100644 --- a/apps/desktop/electron/git-review-ops.test.ts +++ b/apps/desktop/electron/git-review-ops.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { resolveRenamePath } from './git-review-ops' diff --git a/apps/desktop/electron/git-root.test.ts b/apps/desktop/electron/git-root.test.ts index cda56d51a49a5..e4a1758c3d0c1 100644 --- a/apps/desktop/electron/git-root.test.ts +++ b/apps/desktop/electron/git-root.test.ts @@ -2,9 +2,10 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' import { pathToFileURL } from 'node:url' +import { test } from 'vitest' + import { gitRootForIpc } from './git-root' function mkTmpDir() { @@ -19,20 +20,23 @@ test('gitRootForIpc returns null for invalid and device paths', async () => { assert.equal(await gitRootForIpc('file:///%E0%A4%A'), null) }) -test('gitRootForIpc resolves directories files missing descendants and file URLs', async t => { +test('gitRootForIpc resolves directories files missing descendants and file URLs', async () => { const root = mkTmpDir() - t.after(() => fs.rmSync(root, { recursive: true, force: true })) - const gitDir = path.join(root, '.git') - const srcDir = path.join(root, 'src') - const filePath = path.join(srcDir, 'index.ts') - fs.mkdirSync(gitDir) - fs.mkdirSync(srcDir) - fs.writeFileSync(filePath, 'export {}\n', 'utf8') + try { + const gitDir = path.join(root, '.git') + const srcDir = path.join(root, 'src') + const filePath = path.join(srcDir, 'index.ts') + fs.mkdirSync(gitDir) + fs.mkdirSync(srcDir) + fs.writeFileSync(filePath, 'export {}\n', 'utf8') - assert.equal(await gitRootForIpc(root), root) - assert.equal(await gitRootForIpc(srcDir), root) - assert.equal(await gitRootForIpc(filePath), root) - assert.equal(await gitRootForIpc(pathToFileURL(filePath).toString()), root) - assert.equal(await gitRootForIpc(path.join(srcDir, 'missing.ts')), root) + assert.equal(await gitRootForIpc(root), root) + assert.equal(await gitRootForIpc(srcDir), root) + assert.equal(await gitRootForIpc(filePath), root) + assert.equal(await gitRootForIpc(pathToFileURL(filePath).toString()), root) + assert.equal(await gitRootForIpc(path.join(srcDir, 'missing.ts')), root) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } }) diff --git a/apps/desktop/electron/git-worktree-ops.test.ts b/apps/desktop/electron/git-worktree-ops.test.ts index 2d4617c254ca4..3dd39bd304876 100644 --- a/apps/desktop/electron/git-worktree-ops.test.ts +++ b/apps/desktop/electron/git-worktree-ops.test.ts @@ -3,7 +3,8 @@ import { execFileSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { addWorktree, diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.ts index 5d0dc5e212307..1a5852f720af3 100644 --- a/apps/desktop/electron/hardening.test.ts +++ b/apps/desktop/electron/hardening.test.ts @@ -2,9 +2,10 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' import { pathToFileURL } from 'node:url' +import { test } from 'vitest' + import { DEFAULT_FETCH_TIMEOUT_MS, encryptDesktopSecret, @@ -122,171 +123,184 @@ test('resolveRequestedPathForIpc expands ~ to the home directory', () => { ) }) -test('resolveReadableFileForIpc validates existence type size and sensitivity', async t => { +test('resolveReadableFileForIpc validates existence type size and sensitivity', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-hardening-')) - t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })) - const textPath = path.join(tempDir, 'notes.txt') - fs.writeFileSync(textPath, 'hello world', 'utf8') + try { + const textPath = path.join(tempDir, 'notes.txt') + fs.writeFileSync(textPath, 'hello world', 'utf8') - const fromRelative = await resolveReadableFileForIpc('notes.txt', { - baseDir: tempDir, - maxBytes: 256, - purpose: 'File preview' - }) + const fromRelative = await resolveReadableFileForIpc('notes.txt', { + baseDir: tempDir, + maxBytes: 256, + purpose: 'File preview' + }) - assert.equal(fromRelative.resolvedPath, textPath) - assert.equal(fromRelative.stat.size, 11) + assert.equal(fromRelative.resolvedPath, textPath) + assert.equal(fromRelative.stat.size, 11) - const fromFileUrl = await resolveReadableFileForIpc(pathToFileURL(textPath).toString(), { - purpose: 'File preview' - }) + const fromFileUrl = await resolveReadableFileForIpc(pathToFileURL(textPath).toString(), { + purpose: 'File preview' + }) - assert.equal(fromFileUrl.resolvedPath, textPath) + assert.equal(fromFileUrl.resolvedPath, textPath) - const spacedPath = path.join(tempDir, 'notes with spaces.txt') - fs.writeFileSync(spacedPath, 'space ok', 'utf8') + const spacedPath = path.join(tempDir, 'notes with spaces.txt') + fs.writeFileSync(spacedPath, 'space ok', 'utf8') - const fromSpacedFileUrl = await resolveReadableFileForIpc(pathToFileURL(spacedPath).toString(), { - purpose: 'File preview' - }) + const fromSpacedFileUrl = await resolveReadableFileForIpc(pathToFileURL(spacedPath).toString(), { + purpose: 'File preview' + }) - assert.equal(fromSpacedFileUrl.resolvedPath, spacedPath) + assert.equal(fromSpacedFileUrl.resolvedPath, spacedPath) - await assert.rejects( - resolveReadableFileForIpc('missing.txt', { - baseDir: tempDir, - purpose: 'Text preview' - }), - /file does not exist/ - ) + await assert.rejects( + resolveReadableFileForIpc('missing.txt', { + baseDir: tempDir, + purpose: 'Text preview' + }), + /file does not exist/ + ) - const nestedDir = path.join(tempDir, 'directory') - fs.mkdirSync(nestedDir) - await assert.rejects( - resolveReadableFileForIpc(nestedDir, { - purpose: 'Text preview' - }), - /path points to a directory/ - ) + const nestedDir = path.join(tempDir, 'directory') + fs.mkdirSync(nestedDir) + await assert.rejects( + resolveReadableFileForIpc(nestedDir, { + purpose: 'Text preview' + }), + /path points to a directory/ + ) - const largePath = path.join(tempDir, 'large.txt') - fs.writeFileSync(largePath, 'x'.repeat(40), 'utf8') - await assert.rejects( - resolveReadableFileForIpc(largePath, { - maxBytes: 8, - purpose: 'File preview' - }), - /file is too large/ - ) + const largePath = path.join(tempDir, 'large.txt') + fs.writeFileSync(largePath, 'x'.repeat(40), 'utf8') + await assert.rejects( + resolveReadableFileForIpc(largePath, { + maxBytes: 8, + purpose: 'File preview' + }), + /file is too large/ + ) - const envPath = path.join(tempDir, '.env') - fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8') - await assert.rejects( - resolveReadableFileForIpc(envPath, { - purpose: 'File preview' - }), - /blocked for sensitive file/ - ) + const envPath = path.join(tempDir, '.env') + fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8') + await assert.rejects( + resolveReadableFileForIpc(envPath, { + purpose: 'File preview' + }), + /blocked for sensitive file/ + ) - const envTemplatePath = path.join(tempDir, '.env.example') - fs.writeFileSync(envTemplatePath, 'EXAMPLE_TOKEN=value', 'utf8') + const envTemplatePath = path.join(tempDir, '.env.example') + fs.writeFileSync(envTemplatePath, 'EXAMPLE_TOKEN=value', 'utf8') - const envTemplate = await resolveReadableFileForIpc(envTemplatePath, { - purpose: 'File preview' - }) + const envTemplate = await resolveReadableFileForIpc(envTemplatePath, { + purpose: 'File preview' + }) - assert.equal(envTemplate.resolvedPath, envTemplatePath) + assert.equal(envTemplate.resolvedPath, envTemplatePath) + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) + } }) -test('resolveReadableFileForIpc blocks common sensitive files', async t => { +test('resolveReadableFileForIpc blocks common sensitive files', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-sensitive-')) - t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })) - - const sshDir = path.join(tempDir, '.ssh') - fs.mkdirSync(sshDir) - - const blockedFiles = [ - path.join(tempDir, '.env'), - path.join(tempDir, '.npmrc'), - path.join(sshDir, 'id_ed25519'), - path.join(tempDir, 'cert.pem'), - path.join(tempDir, 'cert.p12'), - path.join(tempDir, 'cert.pfx') - ] - for (const filePath of blockedFiles) { - fs.writeFileSync(filePath, 'secret', 'utf8') - await rejectsWithCode(resolveReadableFileForIpc(filePath, { purpose: 'File preview' }), 'sensitive-file') - } + try { + const sshDir = path.join(tempDir, '.ssh') + fs.mkdirSync(sshDir) + + const blockedFiles = [ + path.join(tempDir, '.env'), + path.join(tempDir, '.npmrc'), + path.join(sshDir, 'id_ed25519'), + path.join(tempDir, 'cert.pem'), + path.join(tempDir, 'cert.p12'), + path.join(tempDir, 'cert.pfx') + ] + + for (const filePath of blockedFiles) { + fs.writeFileSync(filePath, 'secret', 'utf8') + await rejectsWithCode(resolveReadableFileForIpc(filePath, { purpose: 'File preview' }), 'sensitive-file') + } - const allowed = path.join(tempDir, '.env.example') - fs.writeFileSync(allowed, 'EXAMPLE_TOKEN=value', 'utf8') - assert.equal((await resolveReadableFileForIpc(allowed, { purpose: 'File preview' })).resolvedPath, allowed) + const allowed = path.join(tempDir, '.env.example') + fs.writeFileSync(allowed, 'EXAMPLE_TOKEN=value', 'utf8') + assert.equal((await resolveReadableFileForIpc(allowed, { purpose: 'File preview' })).resolvedPath, allowed) + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) + } }) -test('resolveReadableFileForIpc blocks symlinks whose realpath is sensitive', async t => { +test('resolveReadableFileForIpc blocks symlinks whose realpath is sensitive', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-realpath-')) - t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })) - - const envPath = path.join(tempDir, '.env') - const linkPath = path.join(tempDir, 'safe-name.txt') - fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8') try { - fs.symlinkSync(envPath, linkPath, 'file') - } catch (error) { - if (error?.code === 'EPERM' || error?.code === 'EACCES') { - t.skip(`symlink creation is not permitted on this platform (${error.code})`) + const envPath = path.join(tempDir, '.env') + const linkPath = path.join(tempDir, 'safe-name.txt') + fs.writeFileSync(envPath, 'SECRET_TOKEN=123', 'utf8') + + try { + fs.symlinkSync(envPath, linkPath, 'file') + } catch (error) { + if (error?.code === 'EPERM' || error?.code === 'EACCES') { + // symlink creation is not permitted on this platform — skip + return + } - return + throw error } - throw error + await rejectsWithCode(resolveReadableFileForIpc(linkPath, { purpose: 'File preview' }), 'sensitive-file') + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) } - - await rejectsWithCode(resolveReadableFileForIpc(linkPath, { purpose: 'File preview' }), 'sensitive-file') }) -test('resolveDirectoryForIpc accepts directories and rejects invalid directory targets', async t => { +test('resolveDirectoryForIpc accepts directories and rejects invalid directory targets', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-dir-')) - t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })) - - const directory = path.join(tempDir, 'project') - const filePath = path.join(tempDir, 'file.txt') - fs.mkdirSync(directory) - fs.writeFileSync(filePath, 'not a directory', 'utf8') - - const resolved = await resolveDirectoryForIpc(directory) - assert.equal(resolved.resolvedPath, directory) - assert.equal(resolved.stat.isDirectory(), true) - await rejectsWithCode(resolveDirectoryForIpc(filePath), 'ENOTDIR') - await rejectsWithCode(resolveDirectoryForIpc(path.join(tempDir, 'missing')), 'ENOENT') - await rejectsWithCode(resolveDirectoryForIpc('\\\\?\\C:\\secret'), 'device-path') + try { + const directory = path.join(tempDir, 'project') + const filePath = path.join(tempDir, 'file.txt') + fs.mkdirSync(directory) + fs.writeFileSync(filePath, 'not a directory', 'utf8') + + const resolved = await resolveDirectoryForIpc(directory) + assert.equal(resolved.resolvedPath, directory) + assert.equal(resolved.stat.isDirectory(), true) + + await rejectsWithCode(resolveDirectoryForIpc(filePath), 'ENOTDIR') + await rejectsWithCode(resolveDirectoryForIpc(path.join(tempDir, 'missing')), 'ENOENT') + await rejectsWithCode(resolveDirectoryForIpc('\\\\?\\C:\\secret'), 'device-path') + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) + } }) -test('resolveDirectoryForIpc accepts directory symlinks or junctions', async t => { +test('resolveDirectoryForIpc accepts directory symlinks or junctions', async () => { const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-dir-link-')) - t.after(() => fs.rmSync(tempDir, { recursive: true, force: true })) - - const directory = path.join(tempDir, 'actual-project') - const linkPath = path.join(tempDir, 'linked-project') - fs.mkdirSync(directory) try { - fs.symlinkSync(directory, linkPath, process.platform === 'win32' ? 'junction' : 'dir') - } catch (error) { - if (error?.code === 'EPERM' || error?.code === 'EACCES') { - t.skip(`directory symlink creation is not permitted on this platform (${error.code})`) + const directory = path.join(tempDir, 'actual-project') + const linkPath = path.join(tempDir, 'linked-project') + fs.mkdirSync(directory) + + try { + fs.symlinkSync(directory, linkPath, process.platform === 'win32' ? 'junction' : 'dir') + } catch (error) { + if (error?.code === 'EPERM' || error?.code === 'EACCES') { + // directory symlink creation is not permitted on this platform — skip + return + } - return + throw error } - throw error + const resolved = await resolveDirectoryForIpc(linkPath) + assert.equal(resolved.resolvedPath, linkPath) + assert.equal(resolved.stat.isDirectory(), true) + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }) } - - const resolved = await resolveDirectoryForIpc(linkPath) - assert.equal(resolved.resolvedPath, linkPath) - assert.equal(resolved.stat.isDirectory(), true) }) diff --git a/apps/desktop/electron/hardening.ts b/apps/desktop/electron/hardening.ts index 5fb113229b387..2d6b533100184 100644 --- a/apps/desktop/electron/hardening.ts +++ b/apps/desktop/electron/hardening.ts @@ -112,6 +112,7 @@ function sensitiveFileBlockReason(filePath) { function ipcPathError(code: any, message: string): Error & { code: any } { const error = new Error(message) as Error & { code: any } + ;(error as any).code = code return error diff --git a/apps/desktop/electron/link-title-window.test.ts b/apps/desktop/electron/link-title-window.test.ts index d67b3eb94ca74..f81190f47dcad 100644 --- a/apps/desktop/electron/link-title-window.test.ts +++ b/apps/desktop/electron/link-title-window.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { createLinkTitleWindow, diff --git a/apps/desktop/electron/link-title-window.ts b/apps/desktop/electron/link-title-window.ts index f636c4b07349b..0920976a528bf 100644 --- a/apps/desktop/electron/link-title-window.ts +++ b/apps/desktop/electron/link-title-window.ts @@ -55,6 +55,7 @@ export function readLinkTitleWindowTitle(window) { if (!window || window.isDestroyed()) { return '' } + const contents = window.webContents if (!contents || contents.isDestroyed()) { diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts index ca7efd8fbdcfe..66ada72bf3d17 100644 --- a/apps/desktop/electron/main.ts +++ b/apps/desktop/electron/main.ts @@ -1,5 +1,4 @@ -type Method = string -import type { ExecFileSyncOptionsWithStringEncoding } from 'node:child_process' + import { execFile, execFileSync, spawn } from 'node:child_process' import crypto from 'node:crypto' import fs from 'node:fs' @@ -30,6 +29,7 @@ import { } from 'electron' import nodePty from 'node-pty' +import { stopBackendChild as stopBackendChildImpl } from './backend-child' import { dashboardFallbackArgs, sourceDeclaresServe } from './backend-command' import { buildDesktopBackendEnv, normalizeHermesHomeRoot } from './backend-env' import { canImportHermesCli, verifyHermesCli } from './backend-probes' @@ -96,6 +96,7 @@ import { } from './hardening' import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window' import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request' +import { decideProfileDeleteAction, profileNameFromDeleteRequest, resolveRouteProfile } from './profile-delete-routing' import { buildSessionWindowUrl, chatWindowWebPreferences, @@ -125,6 +126,8 @@ import { MIN_HEIGHT as WINDOW_MIN_HEIGHT, MIN_WIDTH as WINDOW_MIN_WIDTH } from './window-state' +import { hiddenWindowsChildOptions } from './windows-child-options' +import { buildPathExtCandidates, chooseUpdaterArgs, getVenvSitePackagesEntries, resolveVenvHermesCommand } from './windows-hermes-path' import { readWindowsUserEnvVar } from './windows-user-env' import { isPackagedInstallPath as isPackagedInstallPathUnderRoots } from './workspace-cwd' import { readWslWindowsClipboardImage } from './wsl-clipboard-image' @@ -152,14 +155,6 @@ const APP_ROOT = app.getAppPath() // Dev (`npm run dev`) and prod both load the esbuild output from dist/. const PRELOAD_PATH = path.join(APP_ROOT, 'dist', 'electron-preload.js') -function hiddenWindowsChildOptions(options: any = {}): ExecFileSyncOptionsWithStringEncoding { - if (!IS_WINDOWS || Object.prototype.hasOwnProperty.call(options, 'windowsHide')) { - return options as any - } - - return { ...options, windowsHide: true } as any -} - // Remote displays (SSH X11 forwarding, VNC, RDP) make Chromium's GPU // compositor flicker — accelerated layers can't be presented cleanly over the // wire, so the window flashes during scroll/streaming/animation. Local @@ -870,6 +865,7 @@ function planDesktopLogRotation(size) { if (size < DESKTOP_LOG_MAX_BYTES) { return [] } + const backups = n => Array.from({ length: n }, (_, i) => desktopLogBackupPath(i + 1)) // Pathological boot-loop log: reclaim live + every backup outright. @@ -937,6 +933,7 @@ function flushDesktopLogBufferSync() { if (!desktopLogBuffer) { return } + const chunk = desktopLogBuffer desktopLogBuffer = '' @@ -953,6 +950,7 @@ function flushDesktopLogBufferAsync() { if (!desktopLogBuffer) { return desktopLogFlushPromise } + const chunk = desktopLogBuffer desktopLogBuffer = '' @@ -973,6 +971,7 @@ function scheduleDesktopLogFlush() { if (desktopLogFlushTimer) { return } + desktopLogFlushTimer = setTimeout(() => { desktopLogFlushTimer = null void flushDesktopLogBufferAsync() @@ -985,6 +984,7 @@ function rememberLog(chunk) { if (!text) { return } + const lines = text.split(/\r?\n/).map(line => `[hermes] ${line}`) hermesLog.push(...lines) @@ -1183,11 +1183,13 @@ function broadcastBootProgress() { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:boot-progress', bootProgressState) } @@ -1267,11 +1269,13 @@ function broadcastBootstrapEvent(ev) { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:bootstrap:event', ev) } @@ -1421,9 +1425,7 @@ function findOnPath(command) { // shell-script shim named `hermes` — must not shadow `hermes.cmd`/`hermes.exe`. // The empty entry is kept LAST so callers that already include the extension // (py.exe, pwsh.exe, powershell.exe) still resolve. - const extensions = IS_WINDOWS - ? [...(process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean), ''] - : [''] + const extensions = buildPathExtCandidates(process.env.PATHEXT, IS_WINDOWS) for (const entry of pathEntries) { for (const extension of extensions) { @@ -1443,71 +1445,21 @@ function isCommandScript(command) { } function unwrapWindowsVenvHermesCommand(command, backendArgs) { - if (!IS_WINDOWS || !command || isCommandScript(command)) { - return null - } - - const resolved = path.resolve(String(command)) - - if (!/^hermes(?:\.exe)?$/i.test(path.basename(resolved))) { - return null - } - - const scriptsDir = path.dirname(resolved) - - if (path.basename(scriptsDir).toLowerCase() !== 'scripts') { - return null - } - - const venvRoot = path.dirname(scriptsDir) - const python = getVenvPython(venvRoot) - - if (!fileExists(python)) { - return null - } - - const root = path.dirname(venvRoot) - - // Smoke-test the venv interpreter before trusting it. A venv whose update - // died mid-`pip install` still has python.exe + hermes.exe on disk, but the - // backend dies on its first import (e.g. ModuleNotFoundError: dotenv) before - // the gateway ever binds. Returning it here also BYPASSED the caller's - // `--version` probe, so Retry/"Repair install" re-resolved the same broken - // venv forever instead of falling through to the bootstrap installer. - // Mirror isActiveRuntimeUsable(): probe with the checkout on PYTHONPATH so a - // healthy source-tree venv passes. - if ( - !canImportHermesCli(python, { - env: { - PYTHONPATH: [...(directoryExists(root) ? [root] : []), process.env.PYTHONPATH] - .filter(Boolean) - .join(path.delimiter) - } - }) - ) { - rememberLog( - `Ignoring venv Hermes at ${python}: runtime import probe failed (broken/partial venv); falling through to bootstrap.` - ) - - return null - } - - return { - label: `existing Hermes Python at ${python}`, - command: python, - args: ['-m', 'hermes_cli.main', ...backendArgs], - bootstrap: false, - env: buildDesktopBackendEnv({ - hermesHome: HERMES_HOME, - pythonPathEntries: [...(directoryExists(root) ? [root] : []), ...getVenvSitePackagesEntries(venvRoot)], - venvRoot - }), - kind: 'python', - // Surfaced so backendSupportsServe() can read this runtime's source for the - // `serve` capability check instead of falling back to a heavyweight probe. - root, - shell: false - } + return resolveVenvHermesCommand(command, backendArgs, { + isWindows: IS_WINDOWS, + isCommandScript, + fileExists, + directoryExists, + canImportHermesCli, + getVenvPython, + getVenvSitePackagesEntries, + buildDesktopBackendEnv, + hermesHome: HERMES_HOME, + resolvePath: (...segments) => path.resolve(...segments), + dirname: p => path.dirname(p), + basename: p => path.basename(p), + rememberLog + }) } // Does the resolved runtime understand the `serve` subcommand? The desktop @@ -1526,6 +1478,7 @@ function backendSupportsServe(backend) { if (!backend || !backend.command) { return true } + const key = `${backend.command}::${backend.root || ''}` if (_serveSupportCache.has(key)) { @@ -1855,45 +1808,6 @@ function getVenvPython(venvRoot) { // normal HERMES_DASHBOARD_READY stdout line and no ready-file side channel is // needed. -function getVenvSitePackagesEntries(venvRoot) { - const entries = [] - - if (!venvRoot) { - return entries - } - - if (IS_WINDOWS) { - const sitePackages = path.join(venvRoot, 'Lib', 'site-packages') - - if (directoryExists(sitePackages)) { - entries.push(sitePackages) - } - - return entries - } - - const version = (() => { - try { - const cfg = fs.readFileSync(path.join(venvRoot, 'pyvenv.cfg'), 'utf8') - const match = cfg.match(/^version_info\s*=\s*(\d+\.\d+)/im) - - return match ? match[1].trim() : null - } catch { - return null - } - })() - - if (version) { - const sitePackages = path.join(venvRoot, 'lib', `python${version}`, 'site-packages') - - if (directoryExists(sitePackages)) { - entries.push(sitePackages) - } - } - - return entries -} - function makeDashboardReadyFile() { const dir = path.join(app.getPath('userData'), 'backend-ready') fs.mkdirSync(dir, { recursive: true }) @@ -2326,6 +2240,7 @@ function isShimLocked(shimPath) { if (!IS_WINDOWS) { return false } + let fd try { @@ -2463,6 +2378,7 @@ async function releaseBackendLock(updateRoot, tag) { for (const pid of stragglers) { forceKillProcessTree(pid) } + await new Promise(r => setTimeout(r, 300)) } @@ -2662,7 +2578,7 @@ async function handOffWindowsBootstrapRecovery(reason) { const haveRealInstall = fileExists(venvPython) || fileExists(venvHermes) || fileExists(path.join(updateRoot, '.hermes-bootstrap-complete')) - const updaterArgs = haveRealInstall ? ['--update', '--branch', branch] : ['--repair', '--branch', branch] + const updaterArgs = chooseUpdaterArgs(haveRealInstall, branch) await releaseBackendLockForUpdate(updateRoot) @@ -2757,6 +2673,7 @@ function runningAppBundle() { if (!IS_MAC) { return null } + let dir = path.dirname(app.getPath('exe')) // .../Contents/MacOS for (let i = 0; i < 2; i++) { @@ -3183,6 +3100,7 @@ function resolveRendererIndex() { if (found) { return found } + // Nothing on disk. A packaged build with no renderer bundle blank-pages with // a bare ERR_FILE_NOT_FOUND and no clue why (see #39484). Surface the cause // and the fix before Electron loads the missing file. @@ -3231,6 +3149,7 @@ function resolveHermesCwd() { if (!candidate) { continue } + const resolved = path.resolve(String(candidate)) if (isPackagedInstallPath(resolved)) { @@ -3755,6 +3674,7 @@ function fetchJson(url, token, options: any = {}) { if (body) { req.write(body) } + req.end() }) } @@ -3844,6 +3764,7 @@ function fetchPublicJson(url, options: any = {}) { if (body) { req.write(body) } + req.end() }) } @@ -3961,6 +3882,7 @@ function cacheTitle(key, title) { if (titleCache.size >= TITLE_CACHE_LIMIT) { titleCache.delete(titleCache.keys().next().value) } + titleCache.set(key, title) } @@ -4015,6 +3937,7 @@ function fetchHtmlTitleWithCurl(rawUrl: string): Promise { if (bytes >= TITLE_BYTE_BUDGET) { return } + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) const remaining = TITLE_BYTE_BUDGET - bytes const next = buffer.length > remaining ? buffer.subarray(0, remaining) : buffer @@ -4027,6 +3950,7 @@ function fetchHtmlTitleWithCurl(rawUrl: string): Promise { if (!chunks.length) { return resolve('') } + resolve(parseHtmlTitle(Buffer.concat(chunks).toString('utf8'))) }) }) @@ -4036,6 +3960,7 @@ function getLinkTitleSession() { if (linkTitleSession || !app.isReady()) { return linkTitleSession } + linkTitleSession = session.fromPartition('hermes:link-titles', { cache: false }) linkTitleSession.webRequest.onBeforeRequest((details, callback) => { callback({ cancel: RENDER_TITLE_BLOCKED_RESOURCES.has(details.resourceType) }) @@ -4078,6 +4003,7 @@ function runRenderTitleJob(rawUrl) { if (settled) { return } + settled = true if (hardTimer) { @@ -4087,6 +4013,7 @@ function runRenderTitleJob(rawUrl) { if (graceTimer) { clearTimeout(graceTimer) } + const value = (title || '').replace(/\s+/g, ' ').trim() try { @@ -4112,6 +4039,7 @@ function runRenderTitleJob(rawUrl) { if (graceTimer) { clearTimeout(graceTimer) } + graceTimer = setTimeout(finishWithTitle, RENDER_TITLE_GRACE_MS) } @@ -4193,6 +4121,7 @@ async function resourceBufferFromUrl(rawUrl) { if (!match) { throw new Error('Invalid data URL') } + const mimeType = match[1] || 'application/octet-stream' const encoded = match[3] || '' const buffer = match[2] ? Buffer.from(encoded, 'base64') : Buffer.from(decodeURIComponent(encoded), 'utf8') @@ -4241,6 +4170,7 @@ async function copyImageFromUrl(rawUrl) { if (image.isEmpty()) { throw new Error('Could not read image') } + clipboard.writeImage(image) } @@ -4256,6 +4186,7 @@ async function saveImageFromUrl(rawUrl) { if (result.canceled || !result.filePath) { return false } + await fs.promises.writeFile(result.filePath, buffer) return true @@ -4390,11 +4321,13 @@ function sendPreviewFileChanged(payload) { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:preview-file-changed', payload) } @@ -4415,12 +4348,14 @@ async function watchPreviewFile(rawUrl) { if (timer) { clearTimeout(timer) } + timer = setTimeout(() => { timer = null if (!fileExists(filePath)) { return } + sendPreviewFileChanged({ id, path: filePath, url: pathToFileURL(filePath).toString() }) }, PREVIEW_WATCH_DEBOUNCE_MS) }) @@ -4430,6 +4365,7 @@ async function watchPreviewFile(rawUrl) { if (timer) { clearTimeout(timer) } + watcher.close() } }) @@ -4504,11 +4440,13 @@ function sendBackendExit(payload) { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:backend-exit', payload) } @@ -4516,11 +4454,13 @@ function sendClosePreviewRequested() { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:close-preview-requested') } @@ -4531,11 +4471,13 @@ function sendPowerResume() { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:power-resume') } @@ -4545,6 +4487,7 @@ function registerPowerResumeListeners() { if (powerResumeRegistered) { return } + powerResumeRegistered = true try { @@ -4566,16 +4509,19 @@ function sendOpenUpdatesRequested() { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + webContents.send('hermes:open-updates') if (!mainWindow.isVisible()) { mainWindow.show() } + mainWindow.focus() } @@ -4583,11 +4529,13 @@ function sendWindowStateChanged(nextIsFullscreen?: boolean) { if (!mainWindow || mainWindow.isDestroyed()) { return } + const { webContents } = mainWindow if (!webContents || webContents.isDestroyed()) { return } + const state = getWindowState() if (typeof nextIsFullscreen === 'boolean') { @@ -4732,6 +4680,7 @@ function installDevToolsShortcut(window) { if (!isInspectShortcut) { return } + event.preventDefault() toggleDevTools(window) }) @@ -4760,13 +4709,15 @@ import { installZoomReassertOnWindowEvents, percentToZoomLevel, ZOOM_STORAGE_KEY, - zoomLevelToPercent + zoomLevelToPercent, + zoomWiringForWindowKind } from './zoom' function setAndPersistZoomLevel(window, zoomLevel) { if (!window || window.isDestroyed()) { return } + const next = clampZoomLevel(zoomLevel) window.webContents.setZoomLevel(next) // Keep any open settings UI in sync, including changes made via the @@ -4783,6 +4734,7 @@ function restorePersistedZoomLevel(window) { if (!window || window.isDestroyed()) { return } + window.webContents .executeJavaScript( `(() => { try { return localStorage.getItem(${JSON.stringify(ZOOM_STORAGE_KEY)}) } catch { return null } })()` @@ -4791,6 +4743,7 @@ function restorePersistedZoomLevel(window) { if (stored == null || !window || window.isDestroyed()) { return } + const level = clampZoomLevel(Number(stored)) window.webContents.setZoomLevel(level) }) @@ -4867,6 +4820,7 @@ function installContextMenu(window) { if (template.length) { template.push({ type: 'separator' }) } + template.push( { label: 'Open Link', @@ -5020,6 +4974,7 @@ function getOauthSession() { if (oauthSession || !app.isReady()) { return oauthSession } + oauthSession = session.fromPartition(OAUTH_SESSION_PARTITION) return oauthSession @@ -5035,6 +4990,7 @@ async function hasOauthSessionCookie(baseUrl) { if (!sess) { return false } + const parsed = new URL(baseUrl) try { @@ -5067,6 +5023,7 @@ async function hasLiveOauthSession(baseUrl) { if (!sess) { return false } + const parsed = new URL(baseUrl) try { @@ -5149,6 +5106,7 @@ function openOauthLoginWindow(baseUrl, { silent = false } = {}) { if (settled) { return } + settled = true if (pollTimer) { @@ -5318,6 +5276,7 @@ function fetchJsonViaOauthSession(url, options: any = {}) { if (timedOut) { return } + clearTimeout(timer) const text = Buffer.concat(chunks).toString('utf8') const statusCode = res.statusCode || 500 @@ -5356,6 +5315,7 @@ function fetchJsonViaOauthSession(url, options: any = {}) { if (timedOut) { return } + clearTimeout(timer) reject(error) }) @@ -5363,6 +5323,7 @@ function fetchJsonViaOauthSession(url, options: any = {}) { if (body) { request.write(body) } + request.end() }) } @@ -5768,6 +5729,7 @@ function sanitizeConnectionProfiles(raw: Record) { } = { mode: modeIsRemoteLike(entry.mode) ? entry.mode : 'local' } + const url = String(entry.url || '').trim() if (url) { @@ -6169,7 +6131,7 @@ async function fetchJsonForProfile(profile, path) { } // Issue an arbitrary method against a profile's resolved backend, parsed JSON. -async function requestJsonForProfile(profile: string, path: string, method: Method, body?: string) { +async function requestJsonForProfile(profile: string, path: string, method: string, body?: string) { const conn = await ensureBackend(profile) const url = `${conn.baseUrl}${path}` const opts = { method, body, timeoutMs: DEFAULT_FETCH_TIMEOUT_MS } @@ -6322,19 +6284,7 @@ function resetBootProgressForReconnect() { } function stopBackendChild(child) { - if (!child || child.killed) { - return - } - - try { - if (IS_WINDOWS && Number.isInteger(child.pid)) { - forceKillProcessTree(child.pid) - } else { - child.kill('SIGTERM') - } - } catch { - // Already gone. - } + stopBackendChildImpl(child, { forceKillProcessTree, isWindows: IS_WINDOWS }) } // Soft gateway-mode apply: tear down the primary without resetting boot UI or @@ -6469,6 +6419,7 @@ function touchPoolBackend(profile) { if (!key) { return } + const entry = backendPool.get(key) if (entry) { @@ -6484,6 +6435,7 @@ function evictLruPoolBackends(keep) { if (backendPool.size <= keep) { return } + const now = Date.now() const evictable = [...backendPool.entries()] @@ -6496,6 +6448,7 @@ function evictLruPoolBackends(keep) { if (removable <= 0) { break } + rememberLog(`Evicting idle profile backend "${profile}" (LRU cap ${POOL_MAX_BACKENDS})`) stopPoolBackend(profile) removable -= 1 @@ -6506,6 +6459,7 @@ function startPoolIdleReaper() { if (poolIdleReaper) { return } + poolIdleReaper = setInterval(() => { const now = Date.now() @@ -6658,6 +6612,7 @@ function stopPoolBackend(profile) { if (!entry) { return } + backendPool.delete(profile) stopBackendChild(entry.process) } @@ -6668,6 +6623,7 @@ async function teardownPoolBackendAndWait(profile) { if (!entry) { return } + backendPool.delete(profile) stopBackendChild(entry.process) @@ -6681,59 +6637,38 @@ function stopAllPoolBackends() { } } -function profileNameFromDeleteRequest(request) { - if (!request || String(request.method || 'GET').toUpperCase() !== 'DELETE') { - return null - } - - const match = String(request.path || '').match(/^\/api\/profiles\/([^/?#]+)(?:[?#].*)?$/) - - if (!match) { - return null - } - - let raw = '' - - try { - raw = decodeURIComponent(match[1]) - } catch { - return null - } - - const name = raw.trim() - - if (!name) { - return null - } - - if (name.toLowerCase() === 'default') { - return 'default' - } - - return name.toLowerCase() -} - // Returns the profile name whose backend was torn down, or null when the // request is not a profile-delete. The caller uses this to skip ensureBackend // for the just-torn-down profile — otherwise ensureBackend respawns a pool // backend whose ensure_hermes_home() recreates the deleted profile directory. +// +// The routing *decision* (which branch fires, what profile name gets +// returned) lives in the pure decideProfileDeleteAction() in +// profile-delete-routing.ts; this function only performs the side effects +// that decision calls for. async function prepareProfileDeleteRequest(request) { const profile = profileNameFromDeleteRequest(request) - if (!profile || profile === 'default' || !PROFILE_NAME_RE.test(profile)) { + const decision = decideProfileDeleteAction(profile, { + isDefaultProfile: p => p === 'default', + isValidProfileName: p => PROFILE_NAME_RE.test(p), + primaryProfileKey + }) + + if (decision.action === 'noop') { return null } - if (profile === primaryProfileKey()) { + if (decision.action === 'teardown-primary') { writeActiveDesktopProfile('default') await teardownPrimaryBackendAndWait() - return profile + return decision.profile } - await teardownPoolBackendAndWait(profile) + await teardownPoolBackendAndWait(decision.profile) - return profile + return decision.profile } async function startHermes() { @@ -7014,6 +6949,7 @@ function focusWindow(win) { if (!win.isVisible()) { win.show() } + win.focus() } @@ -7060,7 +6996,7 @@ function spawnSecondaryWindow({ win.on('enter-full-screen', () => sendWindowStateChanged(true)) win.on('leave-full-screen', () => sendWindowStateChanged(false)) - wireCommonWindowHandlers(win) + wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat')) win.loadURL( buildSessionWindowUrl(sessionId, { @@ -7170,9 +7106,9 @@ function spawnPetOverlayWindow(bounds) { // Not supported everywhere — best effort. } - // Pet overlay opts out of global UI zoom (see wireCommonWindowHandlers): it + // Pet overlay opts out of global UI zoom (see zoomWiringForWindowKind): it // owns its window-fit + scale, and inheriting zoom would crop the sprite. - wireCommonWindowHandlers(win, { zoom: false }) + wireCommonWindowHandlers(win, zoomWiringForWindowKind('petOverlay')) win.once('ready-to-show', () => { if (!win.isDestroyed()) { @@ -7304,7 +7240,7 @@ function createWindow() { // window-all-closed from quitting on Windows/Linux). mainWindow.on('closed', () => closePetOverlay()) - wireCommonWindowHandlers(mainWindow) + wireCommonWindowHandlers(mainWindow, zoomWiringForWindowKind('chat')) mainWindow.webContents.on('render-process-gone', (_event, details) => { rememberLog(`[renderer] render-process-gone reason=${details?.reason} exitCode=${details?.exitCode}`) @@ -7451,6 +7387,7 @@ ipcMain.on('hermes:zoom:set-percent', (event, percent) => { if (!window || window.isDestroyed()) { return } + setAndPersistZoomLevel(window, percentToZoomLevel(Number(percent))) }) @@ -7918,7 +7855,7 @@ ipcMain.handle('hermes:api', async (_event, request) => { // backend instead of spawning a fresh pool backend. A freshly spawned // backend calls ensure_hermes_home() which recreates the profile directory, // defeating the deletion and leaving a zombie process. - const routeProfile = tornDownProfile ? null : profile + const routeProfile = resolveRouteProfile(tornDownProfile, profile) const connection = await ensureBackend(routeProfile) const timeoutMs = resolveTimeoutMs(request?.timeoutMs, DEFAULT_FETCH_TIMEOUT_MS) @@ -7952,6 +7889,7 @@ ipcMain.handle('hermes:notify', (_event, payload) => { if (!Notification.isSupported()) { return false } + // Action buttons render only on signed macOS builds; elsewhere they're dropped // and the body click still works. const actions = Array.isArray(payload?.actions) ? payload.actions : [] @@ -7967,6 +7905,7 @@ ipcMain.handle('hermes:notify', (_event, payload) => { if (!mainWindow || mainWindow.isDestroyed()) { return } + focusWindow(mainWindow) if (payload?.sessionId) { @@ -7977,6 +7916,7 @@ ipcMain.handle('hermes:notify', (_event, payload) => { if (!mainWindow || mainWindow.isDestroyed()) { return } + const action = actions[index] if (action?.id) { @@ -8774,6 +8714,7 @@ async function getUninstallSummary() { if (settled) { return } + settled = true resolve(value) } @@ -8968,6 +8909,7 @@ function handleDeepLink(url) { if (!url || typeof url !== 'string') { return } + let parsed try { @@ -8997,6 +8939,7 @@ function handleDeepLink(url) { if (mainWindow.isMinimized()) { mainWindow.restore() } + mainWindow.focus() mainWindow.webContents.send('hermes:deep-link', payload) rememberLog(`[deeplink] delivered ${kind}/${name}`) @@ -9053,6 +8996,7 @@ if (!_gotSingleInstanceLock) { if (mainWindow.isMinimized()) { mainWindow.restore() } + mainWindow.focus() } }) diff --git a/apps/desktop/electron/oauth-net-request.test.ts b/apps/desktop/electron/oauth-net-request.test.ts index 31d9e257d7e10..631119363f046 100644 --- a/apps/desktop/electron/oauth-net-request.test.ts +++ b/apps/desktop/electron/oauth-net-request.test.ts @@ -5,7 +5,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { serializeJsonBody, setJsonRequestHeaders } from './oauth-net-request' diff --git a/apps/desktop/electron/oauth-session-request.test.ts b/apps/desktop/electron/oauth-session-request.test.ts deleted file mode 100644 index 3b6f352d0da06..0000000000000 --- a/apps/desktop/electron/oauth-session-request.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * Regression coverage for the OAuth-session Electron net.request path. - * - * Electron net rejects manual Content-Length/Host headers with - * net::ERR_INVALID_ARGUMENT. Node HTTP helpers may still set Content-Length; - * this guard is scoped to fetchJsonViaOauthSession only. - */ - -import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import test from 'node:test' -import { fileURLToPath } from 'node:url' - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) -const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8') - -function extractFetchJsonViaOauthSession() { - const start = source.indexOf('function fetchJsonViaOauthSession') - const end = source.indexOf('// Mint a single-use WS ticket', start) - assert.notEqual(start, -1, 'fetchJsonViaOauthSession should exist') - assert.notEqual(end, -1, 'fetchJsonViaOauthSession boundary should exist') - - return source.slice(start, end) -} - -test('OAuth Electron net request does not set forbidden Content-Length header', () => { - const fn = extractFetchJsonViaOauthSession() - - assert.match(fn, /electronNet\.request/) - assert.doesNotMatch(fn, /setHeader\(['"]Content-Length['"]/) - assert.match(fn, /request\.write\(body\)/) -}) diff --git a/apps/desktop/electron/profile-delete-respawn.test.ts b/apps/desktop/electron/profile-delete-respawn.test.ts deleted file mode 100644 index 2fbddfc5a596c..0000000000000 --- a/apps/desktop/electron/profile-delete-respawn.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -'use strict' - -import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import test from 'node:test' - -const ELECTRON_DIR = import.meta.dirname - -function readElectronFile(name) { - return fs.readFileSync(path.join(ELECTRON_DIR, name), 'utf8').replace(/\r\n/g, '\n') -} - -// --------------------------------------------------------------------------- -// prepareProfileDeleteRequest must return the torn-down profile name so the -// caller can skip ensureBackend for that profile (issue #52279). -// --------------------------------------------------------------------------- - -test('prepareProfileDeleteRequest returns the torn-down profile name', () => { - const source = readElectronFile('main.ts') - - // Locate the function definition and its closing brace. - const fnStart = source.indexOf('async function prepareProfileDeleteRequest(') - assert.notEqual(fnStart, -1, 'prepareProfileDeleteRequest function not found') - - // The function must contain "return profile" (pool and primary paths). - const fnBody = source.slice(fnStart, fnStart + 800) - const returnProfileCount = (fnBody.match(/return profile/g) || []).length - assert.ok( - returnProfileCount >= 2, - `expected at least 2 "return profile" statements (primary + pool paths), found ${returnProfileCount}` - ) - - // The early-exit guard must return null (not void/undefined). - assert.match(fnBody, /return null/, 'early-exit guard should return null, not undefined') -}) - -test('hermes:api handler routes profile-delete requests to the primary backend', () => { - const source = readElectronFile('main.ts') - - // The handler must capture prepareProfileDeleteRequest's return value. - assert.match( - source, - /const tornDownProfile = await prepareProfileDeleteRequest\(request\)/, - 'handler should capture the return value of prepareProfileDeleteRequest' - ) - - // The handler must use the return value to skip ensureBackend for the - // torn-down profile, routing to the primary (null) instead. - assert.match( - source, - /const routeProfile = tornDownProfile \? null : profile/, - 'handler should route to primary backend when a profile was just torn down' - ) - - // ensureBackend must be called with the conditional route profile. - assert.match( - source, - /const connection = await ensureBackend\(routeProfile\)/, - 'handler should pass routeProfile (not raw profile) to ensureBackend' - ) -}) diff --git a/apps/desktop/electron/profile-delete-routing.test.ts b/apps/desktop/electron/profile-delete-routing.test.ts new file mode 100644 index 0000000000000..6b1bb01da1e41 --- /dev/null +++ b/apps/desktop/electron/profile-delete-routing.test.ts @@ -0,0 +1,82 @@ +import assert from 'node:assert/strict' + +import { test } from 'vitest' + +import { decideProfileDeleteAction, profileNameFromDeleteRequest, resolveRouteProfile } from './profile-delete-routing' + +// --------------------------------------------------------------------------- +// profileNameFromDeleteRequest +// --------------------------------------------------------------------------- + +test('profileNameFromDeleteRequest parses a DELETE /api/profiles/ path', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'DELETE', path: '/api/profiles/worker' }), 'worker') +}) + +test('profileNameFromDeleteRequest lowercases the profile name', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'DELETE', path: '/api/profiles/Worker' }), 'worker') +}) + +test('profileNameFromDeleteRequest returns null for non-DELETE methods', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'GET', path: '/api/profiles/worker' }), null) +}) + +test('profileNameFromDeleteRequest returns null when the path does not match', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'DELETE', path: '/api/sessions' }), null) +}) + +test('profileNameFromDeleteRequest returns null for an empty/whitespace name', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'DELETE', path: '/api/profiles/%20' }), null) +}) + +test('profileNameFromDeleteRequest returns null for an undecodable path segment', () => { + assert.equal(profileNameFromDeleteRequest({ method: 'DELETE', path: '/api/profiles/%E0%A4%A' }), null) +}) + +// --------------------------------------------------------------------------- +// decideProfileDeleteAction +// --------------------------------------------------------------------------- + +const deps = { + isDefaultProfile: p => p === 'default', + isValidProfileName: p => /^[a-z0-9][a-z0-9_-]{0,63}$/.test(p), + primaryProfileKey: () => 'primary-profile' +} + +test('decideProfileDeleteAction is a noop for the default profile', () => { + assert.deepEqual(decideProfileDeleteAction('default', deps), { action: 'noop', profile: null }) +}) + +test('decideProfileDeleteAction is a noop for null (no profile parsed)', () => { + assert.deepEqual(decideProfileDeleteAction(null, deps), { action: 'noop', profile: null }) +}) + +test('decideProfileDeleteAction is a noop for an invalid profile name', () => { + assert.deepEqual(decideProfileDeleteAction('Not Valid!', deps), { action: 'noop', profile: null }) +}) + +test('decideProfileDeleteAction tears down the primary backend for the primary profile', () => { + assert.deepEqual(decideProfileDeleteAction('primary-profile', deps), { + action: 'teardown-primary', + profile: 'primary-profile' + }) +}) + +test('decideProfileDeleteAction tears down the pool backend for any other valid profile', () => { + assert.deepEqual(decideProfileDeleteAction('worker', deps), { action: 'teardown-pool', profile: 'worker' }) +}) + +// --------------------------------------------------------------------------- +// resolveRouteProfile +// --------------------------------------------------------------------------- + +test('resolveRouteProfile routes to the primary backend (null) when a profile was torn down', () => { + assert.equal(resolveRouteProfile('worker', 'other-profile'), null) +}) + +test('resolveRouteProfile passes the requested profile through when nothing was torn down', () => { + assert.equal(resolveRouteProfile(null, 'other-profile'), 'other-profile') +}) + +test('resolveRouteProfile passes through undefined when nothing was torn down and no profile was requested', () => { + assert.equal(resolveRouteProfile(null, undefined), undefined) +}) diff --git a/apps/desktop/electron/profile-delete-routing.ts b/apps/desktop/electron/profile-delete-routing.ts new file mode 100644 index 0000000000000..d8ba5b48e78ca --- /dev/null +++ b/apps/desktop/electron/profile-delete-routing.ts @@ -0,0 +1,95 @@ +// Profile-delete routing logic for the `hermes:api` IPC handler. +// +// When the renderer issues DELETE /api/profiles/, the handler must +// tear down that profile's backend (primary window backend or pool backend) +// and then route the *next* request away from the just-deleted profile's +// pool backend -- spawning a fresh one would call ensure_hermes_home() and +// recreate the profile directory the delete just removed, leaving a zombie +// process behind (issue #52279). +// +// These helpers are pure so they can be unit-tested without Electron. + +/** + * Parse a `hermes:api` request into the profile name a DELETE targets, or + * null when the request is not a profile-delete at all (wrong method, wrong + * path, empty/invalid name). + */ +export function profileNameFromDeleteRequest(request) { + if (!request || String(request.method || 'GET').toUpperCase() !== 'DELETE') { + return null + } + + const match = String(request.path || '').match(/^\/api\/profiles\/([^/?#]+)(?:[?#].*)?$/) + + if (!match) { + return null + } + + let raw = '' + + try { + raw = decodeURIComponent(match[1]) + } catch { + return null + } + + const name = raw.trim() + + if (!name) { + return null + } + + if (name.toLowerCase() === 'default') { + return 'default' + } + + return name.toLowerCase() +} + +export type ProfileDeleteAction = 'noop' | 'teardown-primary' | 'teardown-pool' + +export interface ProfileDeleteDecision { + action: ProfileDeleteAction + profile: string | null +} + +export interface ProfileDeleteDecisionDeps { + isDefaultProfile: (profile: string) => boolean + isValidProfileName: (profile: string) => boolean + primaryProfileKey: () => string +} + +/** + * Pure decision logic for prepareProfileDeleteRequest: given the parsed + * profile name (or null), decide which side-effecting branch the caller + * should take and what profile name it should ultimately report as + * torn-down. No I/O, no async -- the caller performs the actual teardown + * based on `action`. + */ +export function decideProfileDeleteAction( + profile: string | null, + deps: ProfileDeleteDecisionDeps +): ProfileDeleteDecision { + if (!profile || deps.isDefaultProfile(profile) || !deps.isValidProfileName(profile)) { + return { action: 'noop', profile: null } + } + + if (profile === deps.primaryProfileKey()) { + return { action: 'teardown-primary', profile } + } + + return { action: 'teardown-pool', profile } +} + +/** + * Route the next `hermes:api` request away from the primary/window backend + * whenever a profile was just torn down -- otherwise ensureBackend would + * spawn a fresh pool backend for the deleted profile, whose + * ensure_hermes_home() recreates the directory the delete just removed. + */ +export function resolveRouteProfile( + tornDownProfile: string | null, + profile: string | undefined +): string | null | undefined { + return tornDownProfile ? null : profile +} diff --git a/apps/desktop/electron/session-windows.test.ts b/apps/desktop/electron/session-windows.test.ts index cf65d39ac5d4d..fcfca86807302 100644 --- a/apps/desktop/electron/session-windows.test.ts +++ b/apps/desktop/electron/session-windows.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { buildSessionWindowUrl, chatWindowWebPreferences, createSessionWindowRegistry } from './session-windows' diff --git a/apps/desktop/electron/titlebar-overlay-width.test.ts b/apps/desktop/electron/titlebar-overlay-width.test.ts index 543a14cd56f78..0e424fd5c3e86 100644 --- a/apps/desktop/electron/titlebar-overlay-width.test.ts +++ b/apps/desktop/electron/titlebar-overlay-width.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { MACOS_TAHOE_DARWIN_MAJOR, diff --git a/apps/desktop/electron/update-count.test.ts b/apps/desktop/electron/update-count.test.ts index 2c95fbe7adef6..b7e1e89a65832 100644 --- a/apps/desktop/electron/update-count.test.ts +++ b/apps/desktop/electron/update-count.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { resolveBehindCount, shouldCountCommits } from './update-count' diff --git a/apps/desktop/electron/update-marker.test.ts b/apps/desktop/electron/update-marker.test.ts index 2910366f3f932..3da49396cc8d8 100644 --- a/apps/desktop/electron/update-marker.test.ts +++ b/apps/desktop/electron/update-marker.test.ts @@ -14,10 +14,11 @@ import fs from 'fs' import assert from 'node:assert/strict' -import test from 'node:test' import os from 'os' import path from 'path' +import { test } from 'vitest' + import { isPidAlive, markerPath, @@ -40,6 +41,7 @@ const ALIVE: typeof process.kill = () => true // injected kill that "succeeds" = const DEAD: typeof process.kill = () => { const err = new Error('no such process') + ;(err as any).code = 'ESRCH' throw err } @@ -93,6 +95,7 @@ test('isPidAlive: own pid is alive, impossible pid is dead', () => { test('isPidAlive: EPERM counts as alive (process owned by another user)', () => { const eperm = () => { const err = new Error('operation not permitted') + ;(err as any).code = 'EPERM' throw err } diff --git a/apps/desktop/electron/update-rebuild.test.ts b/apps/desktop/electron/update-rebuild.test.ts index c30ccab9e2614..6c2d75245500a 100644 --- a/apps/desktop/electron/update-rebuild.test.ts +++ b/apps/desktop/electron/update-rebuild.test.ts @@ -13,7 +13,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { runRebuildWithRetry, shouldRetryRebuild } from './update-rebuild' diff --git a/apps/desktop/electron/update-relaunch.test.ts b/apps/desktop/electron/update-relaunch.test.ts index 13f2d1df0b683..54e42eabf9b2a 100644 --- a/apps/desktop/electron/update-relaunch.test.ts +++ b/apps/desktop/electron/update-relaunch.test.ts @@ -22,7 +22,8 @@ import { execFileSync } from 'node:child_process' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { buildRelaunchScript, diff --git a/apps/desktop/electron/update-relaunch.ts b/apps/desktop/electron/update-relaunch.ts index cb1c09557681e..46ea789bbf696 100644 --- a/apps/desktop/electron/update-relaunch.ts +++ b/apps/desktop/electron/update-relaunch.ts @@ -63,6 +63,7 @@ function resolveUnpackedRelease(execPath, updateRoot, platform) { if (!execPath || !updateRoot) { return null } + const releaseDir = path.join(updateRoot, 'apps', 'desktop', 'release') const unpacked = path.join(releaseDir, unpackedDirName(platform)) const normalizedExec = path.resolve(String(execPath)) @@ -116,6 +117,7 @@ function sandboxPreflight(unpackedDir, statSync) { if (!unpackedDir) { return { ok: false, reason: 'no-unpacked-dir', path: null } } + const sandboxPath = path.join(unpackedDir, 'chrome-sandbox') let st diff --git a/apps/desktop/electron/update-remote.test.ts b/apps/desktop/electron/update-remote.test.ts index 9244b363f2989..80dc8b1dd0b51 100644 --- a/apps/desktop/electron/update-remote.test.ts +++ b/apps/desktop/electron/update-remote.test.ts @@ -16,7 +16,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { canonicalGitHubRemote, diff --git a/apps/desktop/electron/update-remote.ts b/apps/desktop/electron/update-remote.ts index c1f4b8274208f..1c5a6d57c74c8 100644 --- a/apps/desktop/electron/update-remote.ts +++ b/apps/desktop/electron/update-remote.ts @@ -22,6 +22,7 @@ function canonicalGitHubRemote(url) { if (!url) { return '' } + let value = String(url).trim() if (value.startsWith('git@github.com:')) { diff --git a/apps/desktop/electron/vscode-marketplace.test.ts b/apps/desktop/electron/vscode-marketplace.test.ts index 6c8b8e6b76e65..adbdfbe6f027c 100644 --- a/apps/desktop/electron/vscode-marketplace.test.ts +++ b/apps/desktop/electron/vscode-marketplace.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert' -import test from 'node:test' + +import { test } from 'vitest' import { __testing, extractThemes, readCentralDirectory } from './vscode-marketplace' diff --git a/apps/desktop/electron/window-state.test.ts b/apps/desktop/electron/window-state.test.ts index 25a4fcaa11964..40c8fe1798e2a 100644 --- a/apps/desktop/electron/window-state.test.ts +++ b/apps/desktop/electron/window-state.test.ts @@ -5,7 +5,8 @@ */ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test, vi } from 'vitest' import { computeWindowOptions, @@ -118,8 +119,8 @@ test('computeWindowOptions does not clamp when displays are unknown', () => { // ─── debounce ────────────────────────────────────────────────────────────── -test('debounce coalesces a burst into one trailing run', t => { - t.mock.timers.enable({ apis: ['setTimeout'] }) +test('debounce coalesces a burst into one trailing run', () => { + vi.useFakeTimers() let calls = 0 const d = debounce(() => { @@ -130,14 +131,16 @@ test('debounce coalesces a burst into one trailing run', t => { d() d() assert.equal(calls, 0) - t.mock.timers.tick(249) + vi.advanceTimersByTime(249) assert.equal(calls, 0) - t.mock.timers.tick(1) + vi.advanceTimersByTime(1) assert.equal(calls, 1) + + vi.useRealTimers() }) -test('debounce.flush runs now and cancels the pending timer', t => { - t.mock.timers.enable({ apis: ['setTimeout'] }) +test('debounce.flush runs now and cancels the pending timer', () => { + vi.useFakeTimers() let calls = 0 const d = debounce(() => { @@ -147,6 +150,8 @@ test('debounce.flush runs now and cancels the pending timer', t => { d() d.flush() assert.equal(calls, 1) - t.mock.timers.tick(1000) + vi.advanceTimersByTime(1000) assert.equal(calls, 1) + + vi.useRealTimers() }) diff --git a/apps/desktop/electron/window-state.ts b/apps/desktop/electron/window-state.ts index d443c6aaf183d..56510e8827367 100644 --- a/apps/desktop/electron/window-state.ts +++ b/apps/desktop/electron/window-state.ts @@ -61,6 +61,7 @@ function onScreen(bounds, displays) { if (!a) { return false } + const x = Math.min(bounds.x + bounds.width, a.x + a.width) - Math.max(bounds.x, a.x) const y = Math.min(bounds.y + bounds.height, a.y + a.height) - Math.max(bounds.y, a.y) diff --git a/apps/desktop/electron/windows-child-options.test.ts b/apps/desktop/electron/windows-child-options.test.ts new file mode 100644 index 0000000000000..33fcac3577837 --- /dev/null +++ b/apps/desktop/electron/windows-child-options.test.ts @@ -0,0 +1,132 @@ +import assert from 'node:assert/strict' + +import { test } from 'vitest' + +import { stopBackendChild } from './backend-child' +import { hiddenWindowsChildOptions } from './windows-child-options' + +test('hiddenWindowsChildOptions adds windowsHide:true on Windows when unset', () => { + assert.deepEqual(hiddenWindowsChildOptions({}, true), { windowsHide: true }) +}) + +test('hiddenWindowsChildOptions preserves an existing windowsHide:false on Windows', () => { + assert.deepEqual(hiddenWindowsChildOptions({ windowsHide: false }, true), { windowsHide: false }) +}) + +test('hiddenWindowsChildOptions preserves an existing windowsHide:true on Windows', () => { + assert.deepEqual(hiddenWindowsChildOptions({ windowsHide: true }, true), { windowsHide: true }) +}) + +test('hiddenWindowsChildOptions leaves options unchanged off Windows', () => { + assert.deepEqual(hiddenWindowsChildOptions({}, false), {}) + assert.deepEqual(hiddenWindowsChildOptions({ stdio: 'ignore' }, false), { stdio: 'ignore' }) +}) + +test('hiddenWindowsChildOptions merges windowsHide alongside other options on Windows', () => { + assert.deepEqual(hiddenWindowsChildOptions({ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }, true), { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + windowsHide: true + }) +}) + +test('hiddenWindowsChildOptions defaults isWindows from process.platform when omitted', () => { + const result = hiddenWindowsChildOptions({}) + const expectedHide = process.platform === 'win32' + + assert.equal(Boolean(result.windowsHide), expectedHide) +}) + +function makeChild(overrides: Partial<{ pid: number | null; killed: boolean }> = {}) { + const calls: string[] = [] + + return { + calls, + child: { + kill: (signal: string) => { + calls.push(signal) + }, + killed: overrides.killed ?? false, + pid: 'pid' in overrides ? overrides.pid : 1234 + } + } +} + +test('stopBackendChild tree-kills on Windows when the child has a pid', () => { + const { child, calls } = makeChild({ pid: 4242 }) + const treeKillCalls: number[] = [] + + stopBackendChild(child, { + forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), + isWindows: true + }) + + assert.deepEqual(treeKillCalls, [4242]) + assert.deepEqual(calls, [], 'SIGTERM must not be sent when the Windows tree-kill path is taken') +}) + +test('stopBackendChild sends SIGTERM on non-Windows platforms', () => { + const { child, calls } = makeChild({ pid: 4242 }) + const treeKillCalls: number[] = [] + + stopBackendChild(child, { + forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), + isWindows: false + }) + + assert.deepEqual(calls, ['SIGTERM']) + assert.deepEqual(treeKillCalls, [], 'tree-kill must not run off Windows') +}) + +test('stopBackendChild falls back to SIGTERM on Windows when the pid is not an integer', () => { + const { child, calls } = makeChild({ pid: null }) + const treeKillCalls: number[] = [] + + stopBackendChild(child, { + forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), + isWindows: true + }) + + assert.deepEqual(calls, ['SIGTERM']) + assert.deepEqual(treeKillCalls, []) +}) + +test('stopBackendChild is a no-op for an already-killed child', () => { + const { child, calls } = makeChild({ killed: true }) + const treeKillCalls: number[] = [] + + stopBackendChild(child, { + forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), + isWindows: true + }) + + assert.deepEqual(calls, []) + assert.deepEqual(treeKillCalls, []) +}) + +test('stopBackendChild is a no-op for a null/undefined child', () => { + const treeKillCalls: number[] = [] + + assert.doesNotThrow(() => { + stopBackendChild(null, { forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), isWindows: true }) + stopBackendChild(undefined, { forceKillProcessTree: (pid: number) => treeKillCalls.push(pid), isWindows: true }) + }) + assert.deepEqual(treeKillCalls, []) +}) + +test('stopBackendChild swallows errors thrown by the kill strategy', () => { + const child = { + kill: () => { + throw new Error('ESRCH: no such process') + }, + killed: false, + pid: 99 + } + + assert.doesNotThrow(() => { + stopBackendChild(child, { + forceKillProcessTree: () => {}, + isWindows: false + }) + }) +}) diff --git a/apps/desktop/electron/windows-child-options.ts b/apps/desktop/electron/windows-child-options.ts new file mode 100644 index 0000000000000..547136bad460c --- /dev/null +++ b/apps/desktop/electron/windows-child-options.ts @@ -0,0 +1,37 @@ +/** + * windows-child-options.ts + * + * Shared helper for opting Windows child processes (spawn/execFileSync) into + * a hidden console. Windows spawns a visible console window per child by + * default; every desktop-launched helper process (git, curl, taskkill, the + * backend itself, the bootstrap PowerShell runner, ...) needs `windowsHide: + * true` so the user doesn't see consoles flashing on screen. + * + * Extracted into its own dependency-free module (no electron import) so it + * can be unit-tested directly for both platforms without reading source + * text, and so main.ts and bootstrap-runner.ts share exactly one + * implementation instead of each defining their own copy. + */ + +import type { ExecFileSyncOptionsWithStringEncoding } from 'node:child_process' + +/** + * Merge `windowsHide: true` into `options` when running on Windows, unless + * the caller already specified a `windowsHide` value (which is preserved + * as-is, including an explicit `false` for cases that intentionally want a + * visible/interactive console). No-op on non-Windows platforms. + * + * @param options - spawn/execFileSync options to (possibly) augment. + * @param isWindows - defaults to the real platform check; injectable for + * tests so both branches can be exercised without mocking process.platform. + */ +export function hiddenWindowsChildOptions( + options: any = {}, + isWindows: boolean = process.platform === 'win32' +): ExecFileSyncOptionsWithStringEncoding { + if (!isWindows || Object.prototype.hasOwnProperty.call(options, 'windowsHide')) { + return options as any + } + + return { ...options, windowsHide: true } as any +} diff --git a/apps/desktop/electron/windows-child-process.test.ts b/apps/desktop/electron/windows-child-process.test.ts deleted file mode 100644 index f1d72dedc97ab..0000000000000 --- a/apps/desktop/electron/windows-child-process.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import test from 'node:test' -import { fileURLToPath } from 'node:url' - -const ELECTRON_DIR = path.dirname(fileURLToPath(import.meta.url)) - -// TODO FIXME these tests all grep source code for specific things. This is an antipattern. -// Tests should NEVER read src, only assert behavior. - -function readElectronFile(name) { - return fs.readFileSync(path.join(ELECTRON_DIR, name), 'utf8').replace(/\r\n/g, '\n') -} - -function requireHiddenChildOptions(source, needle) { - const match = needle instanceof RegExp ? needle.exec(source) : null - const index = needle instanceof RegExp ? (match?.index ?? -1) : source.indexOf(needle) - assert.notEqual(index, -1, `missing call site: ${needle}`) - const snippet = source.slice(index, index + 700) - assert.match( - snippet, - /hiddenWindowsChildOptions\(/, - `expected ${needle} to wrap child-process options with hiddenWindowsChildOptions` - ) -} - -test('desktop background child processes opt into hidden Windows consoles', () => { - const source = readElectronFile('main.ts') - - assert.match(source, /function hiddenWindowsChildOptions\(options: any = \{\}\)/) - - requireHiddenChildOptions(source, "execFileSync(\n 'reg'") - requireHiddenChildOptions(source, /execFileSync\(\s*pyExe/) - requireHiddenChildOptions(source, /spawn\(\s*resolveGitBinary\(\)/) - requireHiddenChildOptions(source, "execFileSync('taskkill'") - requireHiddenChildOptions(source, /spawn\(\s*command,\s*args/) - requireHiddenChildOptions(source, "spawn('curl'") - requireHiddenChildOptions(source, /spawn\(\s*backend\.command,\s*backend\.args/) - requireHiddenChildOptions(source, /hermesProcess = spawn\(\s*backend\.command,\s*backend\.args/) - requireHiddenChildOptions(source, /spawn\(\s*py,\s*\['-m', 'hermes_cli\.main', 'uninstall', '--gui-summary'\]/) - - assert.match(source, /function unwrapWindowsVenvHermesCommand\(command, backendArgs\)/) - assert.match(source, /function getVenvSitePackagesEntries\(venvRoot\)/) - assert.match(source, /path\.join\(venvRoot, 'Lib', 'site-packages'\)/) - assert.match(source, /args: \['-m', 'hermes_cli\.main', \.\.\.backendArgs\]/) -}) - -test('desktop backend launches console python so child consoles are inherited, not pythonw', () => { - const source = readElectronFile('main.ts') - - // The flash fix is structural: the backend runs as a console-subsystem - // python.exe under hiddenWindowsChildOptions() (-> CREATE_NO_WINDOW), so it - // owns ONE windowless console that every descendant spawn inherits. Launching - // it as GUI-subsystem pythonw.exe is what made each child allocate (and flash) - // its own console, so the backend command must never be pythonw. - assert.doesNotMatch(source, /pythonw\.exe'\)/, 'backend must not be launched via pythonw.exe') - assert.doesNotMatch( - source, - /function getNoConsoleVenvPython\b/, - 'pythonw-conversion helper should be gone; console python is launched directly' - ) - assert.doesNotMatch( - source, - /function applyWindowsNoConsoleSpawnHints\b/, - 'pythonw spawn-hint rewriter should be gone' - ) - - // Console python restores stdout, so the port is announced on the normal - // HERMES_DASHBOARD_READY stdout line — no ready-file side channel is set. - assert.doesNotMatch(source, /readyFile: true/, 'no backend should opt into the pythonw ready-file path') - - // Both desktop backend launches must still go through hiddenWindowsChildOptions - // so the single backend console is created windowless. - requireHiddenChildOptions(source, /spawn\(\s*backend\.command,\s*backend\.args/) - requireHiddenChildOptions(source, /hermesProcess = spawn\(\s*backend\.command,\s*backend\.args/) -}) - -test('desktop backend teardown tree-kills Windows backend descendants', () => { - const source = readElectronFile('main.ts') - - const helperIndex = source.indexOf('function stopBackendChild(child)') - assert.notEqual(helperIndex, -1, 'missing backend teardown helper') - const helperSnippet = source.slice(helperIndex, helperIndex + 500) - assert.match(helperSnippet, /IS_WINDOWS && Number\.isInteger\(child\.pid\)/) - assert.match(helperSnippet, /forceKillProcessTree\(child\.pid\)/) - assert.match(helperSnippet, /child\.kill\('SIGTERM'\)/) - - const resetIndex = source.indexOf('function resetHermesConnection()') - assert.notEqual(resetIndex, -1, 'missing resetHermesConnection') - const resetSnippet = source.slice(resetIndex, resetIndex + 300) - assert.match(resetSnippet, /stopBackendChild\(hermesProcess\)/) - assert.doesNotMatch(resetSnippet, /hermesProcess\.kill\('SIGTERM'\)/) - - const quitIndex = source.indexOf("app.on('before-quit'") - assert.notEqual(quitIndex, -1, 'missing before-quit handler') - const quitSnippet = source.slice(quitIndex, quitIndex + 900) - assert.match(quitSnippet, /stopBackendChild\(hermesProcess\)/) - assert.doesNotMatch(quitSnippet, /hermesProcess\.kill\('SIGTERM'\)/) -}) - -test('intentional or interactive desktop child processes stay documented', () => { - const source = readElectronFile('main.ts') - - assert.match(source, /windowsHide: false/) - assert.match(source, /handOffWindowsBootstrapRecovery/) - assert.match(source, /'--repair', '--branch'/) - assert.match(source, /'--update', '--branch'/) - assert.match(source, /nodePty\.spawn\(command, args/) - assert.match(source, /spawn\('cmd\.exe', \['\/c', 'start'/) -}) - -test('bootstrap PowerShell runner hides Windows console children', () => { - const source = readElectronFile('bootstrap-runner.ts') - - assert.match(source, /function hiddenWindowsChildOptions\(options = \{\}\)/) - requireHiddenChildOptions(source, /spawn\(\s*ps,\s*fullArgs/) -}) diff --git a/apps/desktop/electron/windows-hermes-path.test.ts b/apps/desktop/electron/windows-hermes-path.test.ts new file mode 100644 index 0000000000000..8600c3501858b --- /dev/null +++ b/apps/desktop/electron/windows-hermes-path.test.ts @@ -0,0 +1,209 @@ +// Unit tests for the pure Windows `hermes` resolution helpers extracted from +// main.ts's findOnPath(), handOffWindowsBootstrapRecovery(), and +// unwrapWindowsVenvHermesCommand(). These pin the two Windows resolution bugs +// that caused desktop reinstall loops: +// 1. buildPathExtCandidates() — PATHEXT extensions must be tried BEFORE the +// empty extension, or an extensionless Git-Bash `hermes` shim shadows +// the real hermes.cmd/hermes.exe. +// 2. chooseUpdaterArgs() — must gate on haveRealInstall (any real-install +// signal), not just the hermes.exe console-script shim, or healthy +// installs get forced into a destructive --repair. +// 3. resolveVenvHermesCommand() — must probe the venv python via +// canImportHermesCli() before trusting it, or a broken venv gets +// re-selected forever instead of falling through to bootstrap. + +import assert from 'node:assert/strict' +import path from 'node:path' + +import { test } from 'vitest' + +import { buildPathExtCandidates, chooseUpdaterArgs, getVenvSitePackagesEntries, resolveVenvHermesCommand } from './windows-hermes-path' + +test('buildPathExtCandidates: Windows tries PATHEXT extensions before the empty extension', () => { + const extensions = buildPathExtCandidates('.COM;.EXE;.BAT;.CMD', true) + + assert.deepEqual(extensions, ['.COM', '.EXE', '.BAT', '.CMD', '']) + assert.equal(extensions[extensions.length - 1], '', 'empty extension must be last, not first') + assert.notEqual(extensions[0], '', 'the buggy empty-extension-first order must not return') +}) + +test('buildPathExtCandidates: defaults to .COM;.EXE;.BAT;.CMD when PATHEXT is unset on Windows', () => { + assert.deepEqual(buildPathExtCandidates(undefined, true), ['.COM', '.EXE', '.BAT', '.CMD', '']) +}) + +test('buildPathExtCandidates: respects a custom PATHEXT, still empty-last', () => { + assert.deepEqual(buildPathExtCandidates('.EXE;.PS1', true), ['.EXE', '.PS1', '']) +}) + +test('buildPathExtCandidates: non-Windows only tries the bare name', () => { + assert.deepEqual(buildPathExtCandidates('.COM;.EXE;.BAT;.CMD', false), ['']) + assert.deepEqual(buildPathExtCandidates(undefined, false), ['']) +}) + +test('chooseUpdaterArgs: gentle --update when a real-install signal is present', () => { + assert.deepEqual(chooseUpdaterArgs(true, 'main'), ['--update', '--branch', 'main']) +}) + +test('chooseUpdaterArgs: destructive --repair only when NO real-install signal is present', () => { + assert.deepEqual(chooseUpdaterArgs(false, 'main'), ['--repair', '--branch', 'main']) +}) + +test('chooseUpdaterArgs: passes the branch through unchanged in both cases', () => { + assert.deepEqual(chooseUpdaterArgs(true, 'release/1.2'), ['--update', '--branch', 'release/1.2']) + assert.deepEqual(chooseUpdaterArgs(false, 'release/1.2'), ['--repair', '--branch', 'release/1.2']) +}) + +function makeDeps(overrides: Partial[2]> = {}) { + return { + isWindows: true, + isCommandScript: () => false, + fileExists: () => true, + directoryExists: () => false, + canImportHermesCli: () => true, + getVenvPython: (venvRoot: string) => `${venvRoot}/Scripts/python.exe`, + getVenvSitePackagesEntries: () => [], + buildDesktopBackendEnv: () => ({ FAKE_ENV: '1' }), + hermesHome: '/fake/hermes-home', + resolvePath: (...segments: string[]) => segments.join('/').replace(/\/+/g, '/'), + dirname: (p: string) => p.slice(0, p.lastIndexOf('/')) || '/', + basename: (p: string) => p.slice(p.lastIndexOf('/') + 1), + rememberLog: () => {}, + ...overrides + } +} + +test('resolveVenvHermesCommand: returns null off Windows', () => { + const deps = makeDeps({ isWindows: false }) + + assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null) +}) + +test('resolveVenvHermesCommand: returns null for a .cmd/.bat script command', () => { + const deps = makeDeps({ isCommandScript: () => true }) + + assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.cmd', [], deps), null) +}) + +test('resolveVenvHermesCommand: returns null when the basename is not hermes/hermes.exe', () => { + const deps = makeDeps() + + assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/python.exe', [], deps), null) +}) + +test('resolveVenvHermesCommand: returns null when the parent dir is not Scripts', () => { + const deps = makeDeps() + + assert.equal(resolveVenvHermesCommand('/root/venv/bin/hermes.exe', [], deps), null) +}) + +test('resolveVenvHermesCommand: returns null when the venv python does not exist on disk', () => { + const deps = makeDeps({ fileExists: () => false }) + + assert.equal(resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', [], deps), null) +}) + +test('resolveVenvHermesCommand: probes the venv python before trusting it (returns null on failed probe)', () => { + let probed = false + + const deps = makeDeps({ + canImportHermesCli: (python: string) => { + probed = true + assert.equal(python, '/root/venv/Scripts/python.exe') + + return false + } + }) + + const result = resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve'], deps) + + assert.equal(probed, true, 'must probe the venv interpreter; a broken venv must not be re-selected forever') + assert.equal(result, null, 'a failed probe must fall through (return null) so the resolver reaches bootstrap') +}) + +test('resolveVenvHermesCommand: returns the resolved python backend descriptor when the probe passes', () => { + const deps = makeDeps() + const result = resolveVenvHermesCommand('/root/venv/Scripts/hermes.exe', ['serve', '--port', '0'], deps) + + assert.ok(result, 'a passing probe must return a backend descriptor, not null') + assert.equal(result.command, '/root/venv/Scripts/python.exe') + assert.deepEqual(result.args, ['-m', 'hermes_cli.main', 'serve', '--port', '0']) + assert.equal(result.bootstrap, false) + assert.equal(result.kind, 'python') + assert.equal(result.shell, false) + assert.deepEqual(result.env, { FAKE_ENV: '1' }) +}) + +test('resolveVenvHermesCommand: is case-insensitive on hermes.exe and the Scripts dir name', () => { + const deps = makeDeps() + + assert.ok(resolveVenvHermesCommand('/root/venv/Scripts/HERMES.EXE', [], deps)) + assert.ok(resolveVenvHermesCommand('/root/venv/SCRIPTS/hermes.exe', [], deps)) +}) + +// ── getVenvSitePackagesEntries ───────────────────────────────────────────── + +test('getVenvSitePackagesEntries: returns Lib/site-packages on Windows when it exists', () => { + const expected = path.join('C:\\venv', 'Lib', 'site-packages') + + const result = getVenvSitePackagesEntries('C:\\venv', { + isWindows: true, + directoryExists: p => p === expected + }) + + assert.deepEqual(result, [expected]) +}) + +test('getVenvSitePackagesEntries: returns empty on Windows when site-packages does not exist', () => { + const result = getVenvSitePackagesEntries('C:\\venv', { + isWindows: true, + directoryExists: () => false + }) + + assert.deepEqual(result, []) +}) + +test('getVenvSitePackagesEntries: reads pyvenv.cfg version on POSIX and resolves lib/pythonX.Y/site-packages', () => { + const result = getVenvSitePackagesEntries('/venv', { + isWindows: false, + directoryExists: p => p === '/venv/lib/python3.12/site-packages', + readFile: () => 'version_info = 3.12.1\n' + }) + + assert.deepEqual(result, ['/venv/lib/python3.12/site-packages']) +}) + +test('getVenvSitePackagesEntries: returns empty on POSIX when pyvenv.cfg is missing', () => { + const result = getVenvSitePackagesEntries('/venv', { + isWindows: false, + directoryExists: () => true, + readFile: () => undefined + }) + + assert.deepEqual(result, []) +}) + +test('getVenvSitePackagesEntries: returns empty on POSIX when pyvenv.cfg has no version_info', () => { + const result = getVenvSitePackagesEntries('/venv', { + isWindows: false, + directoryExists: () => true, + readFile: () => 'home = /usr/bin\n' + }) + + assert.deepEqual(result, []) +}) + +test('getVenvSitePackagesEntries: returns empty on POSIX when version is present but site-packages dir is absent', () => { + const result = getVenvSitePackagesEntries('/venv', { + isWindows: false, + directoryExists: () => false, + readFile: () => 'version_info = 3.11\n' + }) + + assert.deepEqual(result, []) +}) + +test('getVenvSitePackagesEntries: returns empty for a falsy venvRoot', () => { + assert.deepEqual(getVenvSitePackagesEntries('', { isWindows: true, directoryExists: () => true }), []) + assert.deepEqual(getVenvSitePackagesEntries(null, { isWindows: true, directoryExists: () => true }), []) + assert.deepEqual(getVenvSitePackagesEntries(undefined, { isWindows: true, directoryExists: () => true }), []) +}) diff --git a/apps/desktop/electron/windows-hermes-path.ts b/apps/desktop/electron/windows-hermes-path.ts new file mode 100644 index 0000000000000..a40524910ecbc --- /dev/null +++ b/apps/desktop/electron/windows-hermes-path.ts @@ -0,0 +1,287 @@ +/** + * windows-hermes-path.ts + * + * Pure, dependency-injected pieces of Windows `hermes` resolution pulled out + * of main.ts's findOnPath(), handOffWindowsBootstrapRecovery(), and + * unwrapWindowsVenvHermesCommand(). Each of the three functions here pins one + * of the Windows resolution bugs that caused desktop reinstall loops: + * + * 1. buildPathExtCandidates() — findOnPath() tried the empty extension + * FIRST, so an extensionless Git-Bash `hermes` shim shadowed the real + * hermes.cmd/hermes.exe; the shim then failed the --version probe and + * the desktop fell through to a spurious bootstrap/repair. The fix: + * PATHEXT extensions first, empty extension LAST. + * 2. chooseUpdaterArgs() — handOffWindowsBootstrapRecovery() chose + * --update vs the destructive --repair by checking ONLY + * venv\Scripts\hermes.exe (the console-script shim, written at the END + * of venv setup and absent in interrupted states), so it escalated to a + * full venv recreate even on healthy installs. The fix: gate on ANY + * real-install signal, not just the shim. + * 3. resolveVenvHermesCommand() — unwrapWindowsVenvHermesCommand() returned + * the venv python with NO runtime probe (bypassing the caller's + * --version check too), so a venv broken mid-update (e.g. missing + * python-dotenv) was re-selected forever: Retry / "Repair install" + * resolved the same dead interpreter instead of falling through to the + * bootstrap installer. The fix: probe-before-trust. + * + * Kept in a standalone ts module (no Electron imports, dependencies passed + * as parameters) so it can be unit-tested with `node --test` without + * mocking Electron or the filesystem, same pattern as backend-probes.ts and + * backend-command.ts. + */ + +import fs from 'node:fs' +import path from 'node:path' + +/** + * Build the ordered list of extensions findOnPath() should try when + * resolving a bare command name off PATH. + * + * On Windows this MUST try PATHEXT extensions (.COM;.EXE;.BAT;.CMD by + * default) BEFORE the bare/empty-extension name: a real command resolves via + * its .exe/.cmd per Windows command-resolution semantics, and an + * extensionless file (e.g. a Git-Bash shell-script shim named `hermes`) must + * not shadow `hermes.cmd`/`hermes.exe`. The empty entry is kept LAST so + * callers that already include the extension (py.exe, pwsh.exe, + * powershell.exe) still resolve. + * + * On non-Windows platforms there is no PATHEXT concept: only the bare name + * is tried. + * + * @param {string | undefined} pathext - process.env.PATHEXT (or undefined). + * @param {boolean} isWindows + * @returns {string[]} extensions to try, in order, always ending in ''. + */ +export function buildPathExtCandidates(pathext: string | undefined, isWindows: boolean): string[] { + if (!isWindows) { + return [''] + } + + return [...(pathext || '.COM;.EXE;.BAT;.CMD').split(';').filter(Boolean), ''] +} + +/** + * Choose the Windows bootstrap-recovery updater invocation: the gentle + * in-place --update when ANY real-install signal is present, the + * destructive --repair (full venv recreate) otherwise. + * + * haveRealInstall must be computed by the caller from ALL real-install + * signals (venv python interpreter, venv hermes shim, bootstrap-complete + * marker) — gating on just the hermes.exe console-script shim alone is the + * regression this function's callers must avoid: that shim is written at + * the END of venv setup and is absent in exactly the interrupted/quarantined + * states this recovery exists to heal. + * + * @param {boolean} haveRealInstall + * @param {string} branch + * @returns {string[]} updater argv, e.g. ['--update', '--branch', 'main']. + */ +export function chooseUpdaterArgs(haveRealInstall: boolean, branch: string): string[] { + return haveRealInstall ? ['--update', '--branch', branch] : ['--repair', '--branch', branch] +} + +/** + * Resolve the site-packages directory entries for a Python venv. + * + * On Windows, venv layout is `/Lib/site-packages`. + * On POSIX, it's `/lib/python/site-packages` where + * `` (e.g. `3.12`) is read from the venv's `pyvenv.cfg` + * `version_info` field. + * + * Returns only directories that actually exist on disk. Returns an empty + * array when `venvRoot` is falsy or no matching site-packages dir is found. + * + * Extracted from main.ts so the platform branching can be tested without + * reading source text. `isWindows` and `directoryExists` are injectable; + * `readFile` defaults to `fs.readFileSync` but can be overridden for tests. + */ +export function getVenvSitePackagesEntries( + venvRoot: string | undefined | null, + opts: { + isWindows?: boolean + directoryExists?: (p: string) => boolean + readFile?: (p: string) => string | undefined + } = {} +): string[] { + const entries: string[] = [] + + if (!venvRoot) { + return entries + } + + const isWindows = opts.isWindows ?? process.platform === 'win32' + + const directoryExists = opts.directoryExists ?? ((p: string) => { + try { + return fs.statSync(p).isDirectory() + } catch { + return false + } + }) + + const readFile = opts.readFile ?? ((p: string) => { + try { + return fs.readFileSync(p, 'utf8') + } catch { + return undefined + } + }) + + if (isWindows) { + const sitePackages = path.join(venvRoot, 'Lib', 'site-packages') + + if (directoryExists(sitePackages)) { + entries.push(sitePackages) + } + + return entries + } + + const cfg = readFile(path.join(venvRoot, 'pyvenv.cfg')) + + const version = (() => { + if (!cfg) { + return null + } + + const match = cfg.match(/^version_info\s*=\s*(\d+\.\d+)/im) + + return match ? match[1].trim() : null + })() + + if (version) { + const sitePackages = path.join(venvRoot, 'lib', `python${version}`, 'site-packages') + + if (directoryExists(sitePackages)) { + entries.push(sitePackages) + } + } + + return entries +} + +export interface ResolveVenvHermesCommandDeps { + isWindows: boolean + isCommandScript: (command: string) => boolean + fileExists: (filePath: string) => boolean + directoryExists: (filePath: string) => boolean + canImportHermesCli: (python: string, opts?: { env?: Record }) => boolean + getVenvPython: (venvRoot: string) => string + getVenvSitePackagesEntries: (venvRoot: string) => string[] + buildDesktopBackendEnv: (opts: { + hermesHome: string + pythonPathEntries: string[] + venvRoot: string + }) => Record + hermesHome: string + resolvePath: (...segments: string[]) => string + dirname: (p: string) => string + basename: (p: string) => string + rememberLog?: (message: string) => void +} + +/** + * If `command` is a Windows venv `hermes`/`hermes.exe` console-script shim + * (i.e. `/Scripts/hermes(.exe)`), resolve it to the underlying + * venv python invoked as `python -m hermes_cli.main ` — but + * ONLY after smoke-testing that interpreter with canImportHermesCli(). A + * venv whose update died mid-`pip install` still has python.exe + hermes.exe + * on disk, but the backend dies on its first import (e.g. + * ModuleNotFoundError: dotenv) before the gateway ever binds. Returning it + * unprobed also bypasses the caller's `--version` probe, so Retry/"Repair + * install" re-resolves the same broken venv forever instead of falling + * through to the bootstrap installer. + * + * Mirrors isActiveRuntimeUsable(): probes with the checkout on PYTHONPATH so + * a healthy source-tree venv passes. + * + * Returns null when `command` is not a venv hermes shim, the underlying + * python doesn't exist, or the import probe fails. Otherwise returns the + * resolved backend descriptor. + */ +export function resolveVenvHermesCommand( + command: string, + backendArgs: string[], + deps: ResolveVenvHermesCommandDeps +): { + label: string + command: string + args: string[] + bootstrap: false + env: Record + kind: 'python' + root: string + shell: false +} | null { + const { + isWindows, + isCommandScript, + fileExists, + directoryExists, + canImportHermesCli, + getVenvPython, + getVenvSitePackagesEntries, + buildDesktopBackendEnv, + hermesHome, + resolvePath, + dirname, + basename, + rememberLog + } = deps + + if (!isWindows || !command || isCommandScript(command)) { + return null + } + + const resolved = resolvePath(String(command)) + + if (!/^hermes(?:\.exe)?$/i.test(basename(resolved))) { + return null + } + + const scriptsDir = dirname(resolved) + + if (basename(scriptsDir).toLowerCase() !== 'scripts') { + return null + } + + const venvRoot = dirname(scriptsDir) + const python = getVenvPython(venvRoot) + + if (!fileExists(python)) { + return null + } + + const root = dirname(venvRoot) + + if ( + !canImportHermesCli(python, { + env: { + PYTHONPATH: [...(directoryExists(root) ? [root] : []), process.env.PYTHONPATH] + .filter((entry): entry is string => Boolean(entry)) + .join(path.delimiter) + } + }) + ) { + rememberLog?.( + `Ignoring venv Hermes at ${python}: runtime import probe failed (broken/partial venv); falling through to bootstrap.` + ) + + return null + } + + return { + label: `existing Hermes Python at ${python}`, + command: python, + args: ['-m', 'hermes_cli.main', ...backendArgs], + bootstrap: false, + env: buildDesktopBackendEnv({ + hermesHome, + pythonPathEntries: [...(directoryExists(root) ? [root] : []), ...getVenvSitePackagesEntries(venvRoot)], + venvRoot + }), + kind: 'python', + root, + shell: false + } +} diff --git a/apps/desktop/electron/windows-hermes-resolution.test.ts b/apps/desktop/electron/windows-hermes-resolution.test.ts deleted file mode 100644 index 1b91a8acb7f44..0000000000000 --- a/apps/desktop/electron/windows-hermes-resolution.test.ts +++ /dev/null @@ -1,85 +0,0 @@ -// Regression guards for Windows `hermes` resolution in main.ts. -// -// main.ts has no module.exports, so these follow the repo's source-assertion -// test pattern (see windows-child-process.test.ts). They pin the two Windows -// resolution bugs that caused desktop reinstall loops: -// 1. findOnPath() tried the empty extension FIRST, so an extensionless -// Git-Bash `hermes` shim shadowed the real hermes.cmd/hermes.exe; the -// shim then failed the --version probe and the desktop fell through to a -// spurious bootstrap/repair. -// 2. handOffWindowsBootstrapRecovery() chose --update vs the destructive -// --repair by checking ONLY venv\Scripts\hermes.exe (the console-script -// shim, written at the END of venv setup and absent in interrupted -// states), so it escalated to a full venv recreate even on healthy -// installs. -// 3. unwrapWindowsVenvHermesCommand() returned the venv python with NO -// runtime probe (bypassing the caller's --version check too), so a venv -// broken mid-update (e.g. missing python-dotenv) was re-selected forever: -// Retry / "Repair install" resolved the same dead interpreter instead of -// falling through to the bootstrap installer. - -import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import test from 'node:test' -import { fileURLToPath } from 'node:url' - -const __dirname = path.dirname(fileURLToPath(import.meta.url)) - -function readMain() { - return fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8').replace(/\r\n/g, '\n') -} - -test('findOnPath tries PATHEXT extensions before the bare (empty) name on Windows', () => { - const source = readMain() - // Fixed order: PATHEXT first, empty string LAST. - assert.match( - source, - /\(process\.env\.PATHEXT \|\| '\.COM;\.EXE;\.BAT;\.CMD'\)\.split\(';'\)\.filter\(Boolean\), ''\]/, - 'extensions array must end with the empty string, not start with it' - ) - // The buggy empty-first order must not return. - assert.doesNotMatch( - source, - /\['', \.\.\.\(process\.env\.PATHEXT/, - 'empty-extension-first order regressed: an extensionless shim can shadow hermes.cmd/.exe' - ) -}) - -test('Windows bootstrap recovery chooses --update when any real-install signal is present', () => { - const source = readMain() - assert.match(source, /const haveRealInstall =/, 'recovery must compute haveRealInstall') - assert.match(source, /fileExists\(venvPython\)/, 'recovery must accept the venv interpreter as a real-install signal') - assert.match( - source, - /\.hermes-bootstrap-complete/, - 'recovery must accept the bootstrap-complete marker as a real-install signal' - ) - assert.match(source, /updaterArgs = haveRealInstall \? \['--update'/, 'updaterArgs must gate on haveRealInstall') - // The old too-narrow check (only venv\Scripts\hermes.exe) must not return. - assert.doesNotMatch( - source, - /updaterArgs = fileExists\(venvHermes\) \?/, - 'recovery regressed to gating only on the hermes.exe shim, which forces destructive --repair' - ) -}) - -test('unwrapWindowsVenvHermesCommand smoke-tests the venv python before trusting it', () => { - const source = readMain() - const fnStart = source.indexOf('function unwrapWindowsVenvHermesCommand(') - assert.notEqual(fnStart, -1, 'unwrapWindowsVenvHermesCommand must exist in main.ts') - // Slice out just the function body (up to the next top-level function decl) - const fnEnd = source.indexOf('\nfunction ', fnStart + 1) - const body = source.slice(fnStart, fnEnd === -1 ? undefined : fnEnd) - assert.match( - body, - /canImportHermesCli\(python/, - 'unwrap must probe the venv interpreter; returning it unprobed re-selects a broken venv ' + - 'forever (Retry/Repair loop on a mid-update venv missing e.g. python-dotenv)' - ) - assert.match( - body, - /return null\s*\n\s*\}\s*\n\s*return \{/, - 'a failed probe must fall through (return null) so the resolver reaches the bootstrap rung' - ) -}) diff --git a/apps/desktop/electron/windows-user-env.test.ts b/apps/desktop/electron/windows-user-env.test.ts index 17c9a4a7c7e18..6b92650b60a53 100644 --- a/apps/desktop/electron/windows-user-env.test.ts +++ b/apps/desktop/electron/windows-user-env.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import { test } from 'node:test' + +import { test } from 'vitest' import { expandWindowsEnvRefs, parseRegQueryValue, readWindowsUserEnvVar } from './windows-user-env' diff --git a/apps/desktop/electron/windows-user-env.ts b/apps/desktop/electron/windows-user-env.ts index fa91590be41b7..890cd6f4e1034 100644 --- a/apps/desktop/electron/windows-user-env.ts +++ b/apps/desktop/electron/windows-user-env.ts @@ -23,6 +23,7 @@ function parseRegQueryValue(stdout, name) { if (!stdout || !name) { return null } + const typePattern = /^(\S+)\s+(?:REG_SZ|REG_EXPAND_SZ|REG_MULTI_SZ|REG_DWORD|REG_QWORD|REG_BINARY|REG_NONE)\s+(.*)$/ for (const rawLine of String(stdout).split(/\r?\n/)) { @@ -70,6 +71,7 @@ function readWindowsUserEnvVar( if (platform !== 'win32' || !name) { return null } + let stdout try { @@ -88,6 +90,7 @@ function readWindowsUserEnvVar( if (raw == null) { return null } + const expanded = expandWindowsEnvRefs(raw, env).trim() return expanded || null diff --git a/apps/desktop/electron/workspace-cwd.test.ts b/apps/desktop/electron/workspace-cwd.test.ts index 6737c3582821d..1377b9f7d783c 100644 --- a/apps/desktop/electron/workspace-cwd.test.ts +++ b/apps/desktop/electron/workspace-cwd.test.ts @@ -6,7 +6,8 @@ import assert from 'node:assert/strict' import path from 'node:path' -import test from 'node:test' + +import { test } from 'vitest' import { isPackagedInstallPath } from './workspace-cwd' diff --git a/apps/desktop/electron/wsl-clipboard-image.test.ts b/apps/desktop/electron/wsl-clipboard-image.test.ts index 244db40f2a911..311d11ca7dac7 100644 --- a/apps/desktop/electron/wsl-clipboard-image.test.ts +++ b/apps/desktop/electron/wsl-clipboard-image.test.ts @@ -1,5 +1,6 @@ import assert from 'node:assert/strict' -import test from 'node:test' + +import { test } from 'vitest' import { decodeClipboardImageBase64, diff --git a/apps/desktop/electron/wsl-path-bridge.test.ts b/apps/desktop/electron/wsl-path-bridge.test.ts index e6d2bfa87e7ec..79505a1d394ea 100644 --- a/apps/desktop/electron/wsl-path-bridge.test.ts +++ b/apps/desktop/electron/wsl-path-bridge.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict' -import test from 'node:test' +import { test } from 'vitest' import { parseDefaultDistro, resolvePickerDefaultPath, wslPosixToWindowsAccessible } from './wsl-path-bridge' diff --git a/apps/desktop/electron/zoom.test.ts b/apps/desktop/electron/zoom.test.ts index 8be69e813a39a..f965a455b32d6 100644 --- a/apps/desktop/electron/zoom.test.ts +++ b/apps/desktop/electron/zoom.test.ts @@ -5,10 +5,8 @@ */ import assert from 'node:assert/strict' -import fs from 'node:fs' -import path from 'node:path' -import test from 'node:test' -import { fileURLToPath } from 'node:url' + +import { test } from 'vitest' import { clampZoomLevel, @@ -16,7 +14,8 @@ import { percentToZoomLevel, ZOOM_REASSERT_WINDOW_EVENTS, ZOOM_STORAGE_KEY, - zoomLevelToPercent + zoomLevelToPercent, + zoomWiringForWindowKind } from './zoom' test('storage key stays stable so persisted zoom survives upgrades', () => { @@ -66,12 +65,14 @@ test('extreme percentages clamp to the level bounds', () => { test('installZoomReassertOnWindowEvents wires show and restore', () => { const handlers = new Map() + const win = { isDestroyed: () => false, on(event, listener) { handlers.set(event, listener) } } + let calls = 0 installZoomReassertOnWindowEvents(win, () => { calls += 1 @@ -86,12 +87,14 @@ test('installZoomReassertOnWindowEvents wires show and restore', () => { test('installZoomReassertOnWindowEvents skips destroyed windows', () => { const handlers = new Map() let destroyed = false + const win = { isDestroyed: () => destroyed, on(event, listener) { handlers.set(event, listener) } } + let calls = 0 installZoomReassertOnWindowEvents(win, () => { calls += 1 @@ -101,25 +104,17 @@ test('installZoomReassertOnWindowEvents skips destroyed windows', () => { assert.equal(calls, 0) }) -// Source assertion (see windows-child-process.test.ts for the established -// pattern): wireCommonWindowHandlers lives in the electron main entry with heavy -// Electron deps, so we assert the wiring contract against source rather than -// booting a BrowserWindow. Locks in that the pet overlay opts OUT of global UI -// zoom while chat windows keep it — the whole reason this fix is scoped. -test('pet overlay opts out of global UI zoom; chat windows keep it', () => { - const electronDir = path.dirname(fileURLToPath(import.meta.url)) - const source = fs.readFileSync(path.join(electronDir, 'main.ts'), 'utf8').replace(/\r\n/g, '\n') - - // The shared helper gates all zoom wiring behind an opt-out flag. - assert.match(source, /function wireCommonWindowHandlers\(win, \{ zoom = true \}/) - - // The pet overlay window is the only caller that disables zoom. - assert.match(source, /wireCommonWindowHandlers\(win, \{ zoom: false \}\)/) - - // Zoom restore now flows through the shared helper, so createWindow must not - // reassert it directly (that would double-fire and drift from session windows). - const finishLoad = source.indexOf("mainWindow.webContents.once('did-finish-load'") - assert.notEqual(finishLoad, -1, 'missing mainWindow did-finish-load handler') - const snippet = source.slice(finishLoad, finishLoad + 300) - assert.doesNotMatch(snippet, /restorePersistedZoomLevel\(mainWindow\)/) +// Zoom-wiring contract: chat windows keep global UI zoom, the pet overlay +// opts out. Tested via the extracted config — no source-text regex. +test('chat windows opt into zoom', () => { + assert.deepEqual(zoomWiringForWindowKind('chat'), { zoom: true }) +}) + +test('pet overlay opts out of zoom', () => { + assert.deepEqual(zoomWiringForWindowKind('petOverlay'), { zoom: false }) +}) + +test('unknown window kinds default to chat (zoom enabled)', () => { + assert.deepEqual(zoomWiringForWindowKind('unknown'), { zoom: true }) + assert.deepEqual(zoomWiringForWindowKind(undefined), { zoom: true }) }) diff --git a/apps/desktop/electron/zoom.ts b/apps/desktop/electron/zoom.ts index 31182ea64d9b0..d4d769b7f6361 100644 --- a/apps/desktop/electron/zoom.ts +++ b/apps/desktop/electron/zoom.ts @@ -46,7 +46,25 @@ export function installZoomReassertOnWindowEvents(win, reassert) { if (win.isDestroyed?.()) { return } + reassert() }) } } + +/** + * Zoom-wiring decision per window kind. Chat windows (main + session) keep + * global UI zoom; the pet overlay opts out because it sizes its own OS window + * to the sprite and inheriting zoom would crop it. + * + * Extracted so the "pet opts out, everything else opts in" contract is + * unit-testable without booting a BrowserWindow or reading source. + */ +export const ZOOM_WINDOW_CONFIG = { + chat: { zoom: true }, + petOverlay: { zoom: false } +} as const + +export function zoomWiringForWindowKind(kind) { + return ZOOM_WINDOW_CONFIG[kind] ?? ZOOM_WINDOW_CONFIG.chat +} diff --git a/apps/desktop/eslint.config.mjs b/apps/desktop/eslint.config.mjs index ef098c5c8ab76..2a5a925e8ff97 100644 --- a/apps/desktop/eslint.config.mjs +++ b/apps/desktop/eslint.config.mjs @@ -114,6 +114,9 @@ export default [ } }, { - ignores: ['*.config.*'] + files: ['**/*.test.tsx'], + rules: { + 'no-restricted-globals': ['warn', 'document'] + } } ] diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 28f976a99b4f0..0a4fd7f4e9cc6 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -38,14 +38,16 @@ "test:desktop:nsis": "node scripts/test-desktop.mjs nsis", "test:desktop:existing": "node scripts/test-desktop.mjs existing", "test:desktop:fresh": "node scripts/test-desktop.mjs fresh", - "test:desktop:platforms": "node --test electron/bootstrap-platform.test.ts electron/hardening.test.ts electron/backend-env.test.ts electron/backend-probes.test.ts electron/backend-ready.test.ts electron/bootstrap-runner.test.ts electron/connection-config.test.ts electron/dashboard-token.test.ts electron/gateway-ws-probe.test.ts electron/oauth-net-request.test.ts electron/desktop-uninstall.test.ts electron/session-windows.test.ts electron/link-title-window.test.ts electron/workspace-cwd.test.ts electron/fs-read-dir.test.ts electron/wsl-path-bridge.test.ts electron/git-root.test.ts electron/git-worktree-ops.test.ts electron/windows-child-process.test.ts electron/update-remote.test.ts electron/update-count.test.ts electron/update-rebuild.test.ts electron/update-marker.test.ts electron/update-relaunch.test.ts electron/windows-user-env.test.ts electron/wsl-clipboard-image.test.ts electron/titlebar-overlay-width.test.ts electron/window-state.test.ts electron/zoom.test.ts electron/windows-hermes-resolution.test.ts electron/oauth-session-request.test.ts", "typecheck": "tsc -p . --noEmit && tsc -p tsconfig.electron.json --noEmit", "lint": "eslint src/ electron/", "lint:fix": "eslint src/ electron/ --fix", "fmt": "prettier --write 'src/**/*.{ts,tsx}' 'electron/**/*.ts' 'vite.config.ts'", "fix": "npm run lint:fix && npm run fmt", - "test:ui": "vitest run --environment jsdom", - "preview": "node scripts/assert-root-install.mjs && vite preview --host 127.0.0.1 --port 4174" + "test:ui": "vitest run --project ui", + "test:desktop:platforms": "vitest run --project electron", + "test": "vitest run", + "preview": "node scripts/assert-root-install.mjs && vite preview --host 127.0.0.1 --port 4174", + "check": "npm run typecheck && npm run test && npm run test:desktop:all && npm run build" }, "dependencies": { "@assistant-ui/react": "^0.12.28", diff --git a/apps/desktop/scripts/assert-dist-built.mjs b/apps/desktop/scripts/assert-dist-built.mjs index d445edd6ea194..3715eba4e2234 100644 --- a/apps/desktop/scripts/assert-dist-built.mjs +++ b/apps/desktop/scripts/assert-dist-built.mjs @@ -1,5 +1,3 @@ -"use strict" - // Build-time guard: refuse to hand a half-built renderer to electron-builder. // // `npm run pack` / `npm run dist*` are `npm run build && npm run builder`. diff --git a/apps/desktop/scripts/assert-dist-built.test.mjs b/apps/desktop/scripts/assert-dist-built.test.mjs index 7793d359962b5..7c99ac76d0d2d 100644 --- a/apps/desktop/scripts/assert-dist-built.test.mjs +++ b/apps/desktop/scripts/assert-dist-built.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' +import { test } from 'vitest' import { checkDistBuilt } from '../scripts/assert-dist-built.mjs' diff --git a/apps/desktop/scripts/before-pack.mjs b/apps/desktop/scripts/before-pack.mjs index a96b30651dd6d..8b2359dfba636 100644 --- a/apps/desktop/scripts/before-pack.mjs +++ b/apps/desktop/scripts/before-pack.mjs @@ -1,4 +1,3 @@ -'use strict' /** * before-pack.mjs — electron-builder beforePack hook. * diff --git a/apps/desktop/scripts/before-pack.test.mjs b/apps/desktop/scripts/before-pack.test.mjs index 098121e0c6a02..44adf96161879 100644 --- a/apps/desktop/scripts/before-pack.test.mjs +++ b/apps/desktop/scripts/before-pack.test.mjs @@ -2,7 +2,7 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import test from 'node:test' +import { test } from 'vitest' import beforePack, { cleanStaleAppOutDir } from '../scripts/before-pack.mjs' diff --git a/apps/desktop/scripts/stage-native-deps.mjs b/apps/desktop/scripts/stage-native-deps.mjs index ef590c6ecbf5e..af8900e22af91 100644 --- a/apps/desktop/scripts/stage-native-deps.mjs +++ b/apps/desktop/scripts/stage-native-deps.mjs @@ -17,8 +17,10 @@ import { existsSync, mkdirSync, readdirSync, + readFileSync, rmSync } from 'node:fs' +import { spawnSync } from 'node:child_process' import { isMain } from './utils.mjs' const here = dirname(fileURLToPath(import.meta.url)) @@ -77,9 +79,136 @@ function copyBuildRelease(srcDir, destDir) { } } -export function stageNodePty({ platform = process.platform, arch = process.arch } = {}) { - const srcRoot = resolveNodePtyRoot() - const destRoot = resolve(projectRoot, 'dist/node_modules/node-pty') +// ─── binary classification ─────────────────────────────────────────── +// +// .node files are shared libraries in the target platform's native binary +// format. By reading the first few bytes (magic) we can determine which +// platform a given .node was compiled for, without shelling out to `file`. +// +// ELF (\x7fELF) → linux +// Mach-O 32-bit BE (feedface) → darwin +// Mach-O 64-bit BE (feedfacf) → darwin +// Mach-O 32-bit LE (cefaedfe — CIGAM) → darwin +// Mach-O 64-bit LE (cffaedfe — CIGAM_64) → darwin +// Fat/Universal BE (cafebabe) → darwin +// Fat/Universal LE (bebafeca — FAT_CIGAM) → darwin +// PE (MZ DOS header) → win32 +// +// Mach-O and Fat binaries are stored on disk in the host's native byte +// order. On x64/arm64 Darwin (every Apple Silicon + every Intel Mac that +// ships node-pty prebuilds) that is little-endian, so the on-disk magic is +// the CIGAM byte-swapped form, NOT the big-endian MH_MAGIC form. Checking +// only the BE constants misclassifies every real Darwin prebuild as unknown. +// +// Exported for unit testing. + +/** + * Classify a native binary's target platform from its magic bytes. + * Returns `'linux'`, `'darwin'`, `'win32'`, or `null` if unrecognized + * or the file cannot be read. + */ +export function classifyNativeBinary(filePath) { + let buf + try { + buf = readFileSync(filePath, { start: 0, end: 63 }) // first 64 bytes + } catch { + return null + } + if (buf.length < 4) return null + + // ELF: \x7f E L F + if (buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46) { + return 'linux' + } + // Mach-O 32-bit (big-endian / MH_MAGIC): feedface + if (buf[0] === 0xfe && buf[1] === 0xed && buf[2] === 0xfa && buf[3] === 0xce) { + return 'darwin' + } + // Mach-O 64-bit (big-endian / MH_MAGIC_64): feedfacf + if (buf[0] === 0xfe && buf[1] === 0xed && buf[2] === 0xfa && buf[3] === 0xcf) { + return 'darwin' + } + // Mach-O 32-bit (little-endian / MH_CIGAM): cefaedfe + if (buf[0] === 0xce && buf[1] === 0xfa && buf[2] === 0xed && buf[3] === 0xfe) { + return 'darwin' + } + // Mach-O 64-bit (little-endian / MH_CIGAM_64): cffaedfe + if (buf[0] === 0xcf && buf[1] === 0xfa && buf[2] === 0xed && buf[3] === 0xfe) { + return 'darwin' + } + // Fat/Universal binary (big-endian / FAT_MAGIC): cafebabe + if (buf[0] === 0xca && buf[1] === 0xfe && buf[2] === 0xba && buf[3] === 0xbe) { + return 'darwin' + } + // Fat/Universal binary (little-endian / FAT_CIGAM): bebafeca + if (buf[0] === 0xbe && buf[1] === 0xba && buf[2] === 0xfe && buf[3] === 0xca) { + return 'darwin' + } + // PE: MZ DOS header + if (buf[0] === 0x4d && buf[1] === 0x5a) { + return 'win32' + } + return null +} + +/** + * Scan the staged destination tree for .node files and verify each one's + * binary platform matches the requested target. Throws on any mismatch. + * + * This is the fail-closed safety net: even if a prebuild or build/Release + * somehow slipped through with the wrong platform, this catches it before + * the package ships a broken native binary to users. + */ +function validateStagedBinaries(destRoot, targetPlatform) { + const mismatches = [] + function scan(dir, relPrefix) { + if (!existsSync(dir)) return + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isDirectory()) { + scan(join(dir, entry.name), `${relPrefix}${entry.name}/`) + continue + } + if (!entry.name.endsWith('.node')) continue + const fullPath = join(dir, entry.name) + const classified = classifyNativeBinary(fullPath) + if (classified !== targetPlatform) { + mismatches.push({ file: `${relPrefix}${entry.name}`, classified, expected: targetPlatform }) + } + } + } + scan(join(destRoot, 'prebuilds'), 'prebuilds/') + scan(join(destRoot, 'build', 'Release'), 'build/Release/') + if (mismatches.length > 0) { + throw new Error( + `[stage-native-deps] native binary platform mismatch (target=${targetPlatform}):\n` + + mismatches + .map((m) => ` ${m.file}: expected ${m.expected}, got ${m.classified ?? 'unknown'}`) + .join('\n') + + `\nRefusing to stage a binary compiled for the wrong platform.` + ) + } +} + +/** + * Stage node-pty's native runtime dependencies into `destRoot`. + * + * Exported separately from `stageNodePty` so tests can supply a fake + * node-pty source tree without going through real module resolution. + * + * Strategy (fail-closed): + * + * 1. Copy the matching prebuild (`prebuilds/-/`) if present. + * 2. Copy `build/Release/` **only when the target matches the host** — + * build/Release contains a binary compiled for the host's platform/arch, + * so staging it for a different target ships a broken app. + * 3. If no native binary was staged: + * - Same platform as host, different arch → run `electron-rebuild --arch`. + * - Different platform from host → throw (cannot cross-compile native + * modules; build on the target platform or provide a prebuild). + * 4. Validate every staged `.node` file's binary platform matches the target. + */ +export function stageNodePtyInto(srcRoot, destRoot, { platform = process.platform, arch = process.arch } = {}) { + const hostMatch = platform === process.platform && arch === process.arch rmSync(destRoot, { recursive: true, force: true }) mkdirSync(destRoot, { recursive: true }) @@ -91,11 +220,6 @@ export function stageNodePty({ platform = process.platform, arch = process.arch // lib/**/*.js — the JS surface node-pty's `main` points into. copyGlobByExt(join(srcRoot, 'lib'), join(destRoot, 'lib'), ['.js']) - // build/Release/* — present when node-pty was compiled locally - // (e.g. no prebuild available for this Electron ABI/platform combo). - // Some installs won't have this at all if prebuild-install succeeded. - copyBuildRelease(join(srcRoot, 'build/Release'), join(destRoot, 'build/Release')) - // prebuilds/-/* — the prebuild-install payload for the // *target* we're packaging, not necessarily the host running this script. // Explicit extensions only, to skip the ~25MB of Windows .pdb symbols @@ -117,19 +241,81 @@ export function stageNodePty({ platform = process.platform, arch = process.arch cpSync(join(prebuildDir, entry.name), join(destPrebuild, entry.name)) } } - } else { - console.warn( - `[stage-native-deps] no prebuild found at prebuilds/${platform}-${arch} for node-pty. ` + - `If build/Release/* above is also empty, this target will fail at runtime. ` + - `Run "npx electron-rebuild -w node-pty" for this target, or check that ` + - `node-pty's published prebuilds cover ${platform}-${arch}.` + } + + // build/Release/* — present when node-pty was compiled locally + // (e.g. no prebuild available for this Electron ABI/platform combo). + // Only stage this when the target matches the host, because + // build/Release contains a binary compiled for the *host's* platform + // and architecture. Staging a host binary for a different target (e.g. + // a macOS Mach-O .node staged for a linux-arm64 target) ships a broken + // app that crashes the first time a terminal is spawned. + if (hostMatch) { + const buildReleaseDir = join(srcRoot, 'build/Release') + copyBuildRelease(buildReleaseDir, join(destRoot, 'build/Release')) + } + + // Check whether a native binary for this target was staged. + const stagedDirs = [ + join(destRoot, 'prebuilds', `${platform}-${arch}`), + join(destRoot, 'build/Release') + ] + const hasNativeBinary = stagedDirs.some((dir) => { + if (!existsSync(dir)) return false + return readdirSync(dir, { recursive: true }).some((name) => String(name).endsWith('.node')) + }) + + if (!hasNativeBinary) { + if (platform !== process.platform) { + throw new Error( + `[stage-native-deps] no prebuilt binary for ${platform}-${arch} and ` + + `cannot cross-compile native modules from ${process.platform}-${process.arch}. ` + + `Build on the target platform or provide a prebuild.` + ) + } + // Same platform, possibly different arch — rebuild from source with + // the target architecture so electron-rebuild produces the correct + // binary rather than defaulting to the host's arch. + console.log( + `[stage-native-deps] no native binary for ${platform}-${arch}; ` + + `running electron-rebuild (target arch: ${arch})...` ) + const rebuildArgs = [ + '../../node_modules/.bin/electron-rebuild', + '-f', + '-w', + 'node-pty', + '--arch', + arch + ] + const result = spawnSync(process.execPath, rebuildArgs, { + cwd: projectRoot, + stdio: 'inherit' + }) + if (result.status !== 0) { + throw new Error( + `electron-rebuild failed for ${platform}-${arch} (exit ${result.status}). ` + + `Cannot stage node-pty without a native binary.` + ) + } + // Re-copy build/Release after electron-rebuild populated it. + const buildReleaseDir = join(srcRoot, 'build/Release') + copyBuildRelease(buildReleaseDir, join(destRoot, 'build/Release')) } + // Validate every staged .node binary matches the target platform. + validateStagedBinaries(destRoot, platform) + console.log(`[stage-native-deps] staged node-pty (${platform}-${arch}) -> ${destRoot}`) return destRoot } +export function stageNodePty({ platform = process.platform, arch = process.arch } = {}) { + const srcRoot = resolveNodePtyRoot() + const destRoot = resolve(projectRoot, 'dist/node_modules/node-pty') + return stageNodePtyInto(srcRoot, destRoot, { platform, arch }) +} + // Allow direct CLI invocation: node scripts/stage-native-deps.mjs [platform] [arch] if (isMain(import.meta.url)) { const [platform, arch] = process.argv.slice(2) diff --git a/apps/desktop/scripts/stage-native-deps.test.mjs b/apps/desktop/scripts/stage-native-deps.test.mjs new file mode 100644 index 0000000000000..65e1bb5d3022c --- /dev/null +++ b/apps/desktop/scripts/stage-native-deps.test.mjs @@ -0,0 +1,285 @@ +import assert from 'node:assert/strict' +import fs, { existsSync } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { test } from 'vitest' + +import { + stageNodePtyInto, + classifyNativeBinary +} from '../scripts/stage-native-deps.mjs' + +const { join } = path + +// ─── fixtures ────────────────────────────────────────────────────── +// +// Create minimal fake .node files with correct magic bytes so the +// binary classifier and the staging validator exercise real code paths +// without needing actual native modules. + +/** Write a fake .node file with the given platform's magic bytes. */ +function makeFakeNode(filePath, platform) { + const headers = { + linux: Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x00, 0x00, 0x00, 0x00]), // ELF + // On x64/arm64 Darwin, Mach-O binaries are stored little-endian on disk + // (MH_CIGAM_64 = cffaedfe). This is the form node-pty's prebuilds ship in. + darwin: Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x00, 0x00, 0x00, 0x00]), // Mach-O 64-bit LE (CIGAM_64) + win32: Buffer.from([0x4d, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]), // MZ (PE) + } + fs.mkdirSync(path.dirname(filePath), { recursive: true }) + fs.writeFileSync(filePath, headers[platform] ?? headers.linux) +} + +/** Create a minimal fake node-pty source tree in a temp dir. */ +function makeFakeNodePty(srcRoot, { prebuildPlatform, prebuildArch } = {}) { + fs.mkdirSync(srcRoot, { recursive: true }) + fs.writeFileSync(join(srcRoot, 'package.json'), JSON.stringify({ name: 'node-pty', main: 'lib/index.js' })) + fs.mkdirSync(join(srcRoot, 'lib'), { recursive: true }) + fs.writeFileSync(join(srcRoot, 'lib', 'index.js'), 'module.exports = {};') + + if (prebuildPlatform && prebuildArch) { + const prebuildDir = join(srcRoot, 'prebuilds', `${prebuildPlatform}-${prebuildArch}`) + makeFakeNode(join(prebuildDir, 'pty.node'), prebuildPlatform) + } +} + +// ─── classifyNativeBinary tests ───────────────────────────────────── + +test('classifyNativeBinary detects ELF as linux', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0x7f, 0x45, 0x4c, 0x46, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'linux') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Mach-O 64-bit BE as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xfe, 0xed, 0xfa, 0xcf, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Mach-O 64-bit LE (CIGAM_64) as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Mach-O 32-bit BE as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xfe, 0xed, 0xfa, 0xce, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Mach-O 32-bit LE (CIGAM) as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xce, 0xfa, 0xed, 0xfe, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Fat/Universal BE (cafebabe) as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xca, 0xfe, 0xba, 0xbe, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects Fat/Universal LE (bebafeca / FAT_CIGAM) as darwin', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0xbe, 0xba, 0xfe, 0xca, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'darwin') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary detects PE (MZ) as win32', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0x4d, 0x5a, 0x00, 0x00, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), 'win32') + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary returns null for unrecognized magic', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const f = join(tmp, 'test.node') + fs.writeFileSync(f, Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00])) + assert.equal(classifyNativeBinary(f), null) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('classifyNativeBinary returns null for a missing file', () => { + assert.equal(classifyNativeBinary('/nonexistent/path/to/thing.node'), null) +}) + +// ─── cross-target regression tests ────────────────────────────────── +// +// The core bug: stageNodePty receives { platform, arch } from +// electron-builder but unconditionally copies host build/Release, staging +// a host binary for a foreign target. These tests prove the fix: +// +// 1. A host build/Release must NOT be staged for a foreign platform. +// 2. A matching prebuild IS staged for a foreign target. +// 3. A foreign target with no prebuild throws (fail closed). +// 4. A host build/Release IS staged for a matching target. +// 5. Validation rejects a binary whose magic bytes don't match the target. + +test('cross-target: host build/Release is NOT staged for a foreign platform', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const srcRoot = join(tmp, 'node-pty') + const destRoot = join(tmp, 'dest') + + // Create a node-pty tree with ONLY a host build/Release (no prebuild). + makeFakeNodePty(srcRoot) + const buildReleaseDir = join(srcRoot, 'build', 'Release') + makeFakeNode(join(buildReleaseDir, 'pty.node'), process.platform) + + // Request a foreign platform (different from the host). + const foreignPlatform = process.platform === 'linux' ? 'darwin' : 'linux' + + assert.throws( + () => stageNodePtyInto(srcRoot, destRoot, { platform: foreignPlatform, arch: 'x64' }), + /cannot cross-compile/i + ) + + // build/Release must NOT have been copied to the dest tree. + assert.equal( + existsSync(join(destRoot, 'build', 'Release', 'pty.node')), + false, + 'host build/Release .node must not be staged for a foreign target' + ) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('cross-target: matching prebuild IS staged for a foreign target', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const srcRoot = join(tmp, 'node-pty') + const destRoot = join(tmp, 'dest') + + // Host is (say) darwin. Request linux-x64, which has a prebuild. + const foreignPlatform = process.platform === 'linux' ? 'darwin' : 'linux' + makeFakeNodePty(srcRoot, { prebuildPlatform: foreignPlatform, prebuildArch: 'x64' }) + + // Also create a host build/Release that should NOT be staged. + makeFakeNode(join(srcRoot, 'build', 'Release', 'pty.node'), process.platform) + + stageNodePtyInto(srcRoot, destRoot, { platform: foreignPlatform, arch: 'x64' }) + + // The foreign prebuild must be staged. + const stagedPrebuild = join(destRoot, 'prebuilds', `${foreignPlatform}-x64`, 'pty.node') + assert.equal(existsSync(stagedPrebuild), true, 'foreign prebuild must be staged') + + // The host build/Release must NOT be staged. + assert.equal( + existsSync(join(destRoot, 'build', 'Release', 'pty.node')), + false, + 'host build/Release must not be staged for a foreign target' + ) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('cross-target: foreign target with no prebuild throws (fail closed)', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const srcRoot = join(tmp, 'node-pty') + const destRoot = join(tmp, 'dest') + + // Create a tree with a host build/Release but no foreign prebuild. + makeFakeNodePty(srcRoot) + makeFakeNode(join(srcRoot, 'build', 'Release', 'pty.node'), process.platform) + + const foreignPlatform = process.platform === 'linux' ? 'darwin' : 'linux' + + assert.throws( + () => stageNodePtyInto(srcRoot, destRoot, { platform: foreignPlatform, arch: 'x64' }), + /cannot cross-compile/i + ) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('host-target: host build/Release IS staged for a matching target', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const srcRoot = join(tmp, 'node-pty') + const destRoot = join(tmp, 'dest') + + makeFakeNodePty(srcRoot) + makeFakeNode(join(srcRoot, 'build', 'Release', 'pty.node'), process.platform) + + stageNodePtyInto(srcRoot, destRoot, { platform: process.platform, arch: process.arch }) + + assert.equal( + existsSync(join(destRoot, 'build', 'Release', 'pty.node')), + true, + 'host build/Release must be staged for a matching target' + ) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) + +test('validation rejects a staged binary with the wrong platform magic', () => { + const tmp = fs.mkdtempSync(join(os.tmpdir(), 'hermes-stage-')) + try { + const srcRoot = join(tmp, 'node-pty') + const destRoot = join(tmp, 'dest') + + // Create a prebuild dir that claims to be linux-x64 but contains + // a darwin (Mach-O) binary. This simulates the original bug where + // a host binary ends up in a foreign target's prebuild slot. + makeFakeNodePty(srcRoot, { prebuildPlatform: 'linux', prebuildArch: 'x64' }) + // Overwrite the prebuild .node with the WRONG platform magic. + makeFakeNode(join(srcRoot, 'prebuilds', 'linux-x64', 'pty.node'), 'darwin') + + assert.throws( + () => stageNodePtyInto(srcRoot, destRoot, { platform: 'linux', arch: 'x64' }), + /platform mismatch/i + ) + } finally { + fs.rmSync(tmp, { recursive: true, force: true }) + } +}) diff --git a/apps/desktop/scripts/test-desktop.mjs b/apps/desktop/scripts/test-desktop.mjs index bbda8ec5ee4ac..ec94ddc5e7fc5 100644 --- a/apps/desktop/scripts/test-desktop.mjs +++ b/apps/desktop/scripts/test-desktop.mjs @@ -42,7 +42,7 @@ const APP = (() => { const unpacked = path.join(RELEASE_ROOT, 'linux-unpacked') return { appPath: unpacked, - binary: path.join(unpacked, 'hermes'), + binary: path.join(unpacked, 'Hermes'), resourcesPath: path.join(unpacked, 'resources'), asarPath: path.join(unpacked, 'resources', 'app.asar'), unpackedDistIndex: path.join(unpacked, 'resources', 'app.asar.unpacked', 'dist', 'index.html') @@ -108,10 +108,9 @@ function expectedNativeDepPaths() { function ensurePlatformBuilds() { if (PLATFORM === 'darwin') return if (PLATFORM === 'win32') return + if (PLATFORM === 'linux') return die( - `Desktop bundle validation is only wired for darwin / win32 today; platform=${PLATFORM} ` + - `is not yet supported. The thin-installer story for Linux ships in Phase 2 alongside ` + - `install.sh's stage protocol.` + `Desktop bundle validation is only wired for darwin / win32 / linux; platform=${PLATFORM} is not supported.` ) } diff --git a/apps/desktop/scripts/write-build-stamp.mjs b/apps/desktop/scripts/write-build-stamp.mjs index 694bd9e8dd287..005db35d17729 100644 --- a/apps/desktop/scripts/write-build-stamp.mjs +++ b/apps/desktop/scripts/write-build-stamp.mjs @@ -1,5 +1,3 @@ -"use strict" - /** * Writes apps/desktop/build/install-stamp.json with the git ref the desktop * .exe should pin to at first-launch bootstrap time. This file ships inside diff --git a/apps/desktop/src/app/chat/composer/attachments.test.tsx b/apps/desktop/src/app/chat/composer/attachments.test.tsx index 0ea85811315f0..52e8f6bf98e89 100644 --- a/apps/desktop/src/app/chat/composer/attachments.test.tsx +++ b/apps/desktop/src/app/chat/composer/attachments.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, render, screen } from '@testing-library/react' +import { act, cleanup, render, screen } from '@testing-library/react' import { afterEach, describe, expect, it } from 'vitest' import { I18nProvider } from '@/i18n/context' @@ -10,12 +10,17 @@ function makeAttachment(id: string, label = 'test.pdf'): ComposerAttachment { return { id, kind: 'file', label } } -function renderWithI18n(ui: React.ReactNode) { - return render( - ({}), saveConfig: async () => ({ ok: true }) }}> - {ui} - - ) +async function renderWithI18n(ui: React.ReactNode) { + let result: ReturnType + await act(async () => { + result = render( + ({}), saveConfig: async () => ({ ok: true }) }}> + {ui} + + ) + }) + + return result! } describe('AttachmentList', () => { @@ -23,23 +28,22 @@ describe('AttachmentList', () => { cleanup() }) - it('renders valid attachments', () => { + it('renders valid attachments', async () => { const attachments = [makeAttachment('a', 'doc.pdf'), makeAttachment('b', 'img.png')] - renderWithI18n() + await renderWithI18n() expect(screen.getByText('doc.pdf')).toBeDefined() expect(screen.getByText('img.png')).toBeDefined() }) - it('renders empty list without error', () => { - renderWithI18n() + it('renders empty list without error', async () => { + const { container } = await renderWithI18n() - const container = - screen.getByTestId?.('composer-attachments') ?? document.querySelector('[data-slot="composer-attachments"]') + const attachmentList = container.querySelector('[data-slot="composer-attachments"]') - expect(container).toBeDefined() + expect(attachmentList).toBeDefined() }) - it('does not crash when attachments array contains undefined entries', () => { + it('does not crash when attachments array contains undefined entries', async () => { // Repro: session switch can leave stale/undefined entries in the // attachments array, causing a TypeError at attachment.refText. const attachments = [ @@ -48,21 +52,17 @@ describe('AttachmentList', () => { makeAttachment('b', 'also-good.png') ] - expect(() => { - renderWithI18n() - }).not.toThrow() + await expect(renderWithI18n()).resolves.toBeTruthy() // Only valid attachments should render expect(screen.getByText('good.pdf')).toBeDefined() expect(screen.getByText('also-good.png')).toBeDefined() }) - it('does not crash when attachments array contains null entries', () => { + it('does not crash when attachments array contains null entries', async () => { const attachments = [null as unknown as ComposerAttachment, makeAttachment('a', 'valid.txt')] - expect(() => { - renderWithI18n() - }).not.toThrow() + await expect(renderWithI18n()).resolves.toBeTruthy() expect(screen.getByText('valid.txt')).toBeDefined() }) diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx index 51e5539bac9ee..650900a42e9d4 100644 --- a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx +++ b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx @@ -19,7 +19,7 @@ describe('PreviewPane console state', () => { vi.unstubAllGlobals() }) - it('does not watch backend-only remote filesystem previews locally', () => { + it('does not watch backend-only remote filesystem previews locally', async () => { const watchPreviewFile = vi.fn(async () => ({ id: 'watch-1', path: '/remote/file.txt' })) const onPreviewFileChanged = vi.fn(() => vi.fn()) $connection.set({ mode: 'remote' } as never) @@ -31,38 +31,43 @@ describe('PreviewPane console state', () => { } }) - render( - - ) + await act(async () => { + render( + + ) + }) expect(watchPreviewFile).not.toHaveBeenCalled() expect(onPreviewFileChanged).not.toHaveBeenCalled() }) - it('does not rebuild the pane titlebar group for streamed console logs', () => { + it('does not rebuild the pane titlebar group for streamed console logs', async () => { const setTitlebarToolGroup = vi.fn() - const rendered = render( - - ) + let rendered!: ReturnType + await act(async () => { + rendered = render( + + ) + }) const initialCalls = setTitlebarToolGroup.mock.calls.length const webview = rendered.container.querySelector('webview') diff --git a/apps/desktop/src/app/messaging/index.test.tsx b/apps/desktop/src/app/messaging/index.test.tsx index a7d9273c0c902..b078a2043b1d7 100644 --- a/apps/desktop/src/app/messaging/index.test.tsx +++ b/apps/desktop/src/app/messaging/index.test.tsx @@ -1,5 +1,5 @@ // @vitest-environment jsdom -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { MemoryRouter } from 'react-router-dom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -53,12 +53,16 @@ afterEach(() => { async function renderMessaging() { const { MessagingView } = await import('./index') + let result: ReturnType + await act(async () => { + result = render( + + + + ) + }) - return render( - - - - ) + return result! } describe('MessagingView setup-guide link', () => { @@ -82,7 +86,9 @@ describe('MessagingView setup-guide link', () => { await renderMessaging() const link = await screen.findByText('Open setup guide') - fireEvent.click(link) + await act(async () => { + fireEvent.click(link) + }) await waitFor(() => expect(openExternalLink).toHaveBeenCalledWith(docsUrl)) }) diff --git a/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx b/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx index 119bb51a04025..3af7455a9535d 100644 --- a/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-preview-routing.test.tsx @@ -62,9 +62,9 @@ describe('usePreviewRouting', () => { $currentCwd.set('/work') $messages.set([]) $previewTarget.set(null) - window.localStorage.clear() clearSessionPreviewRegistry() handleEvent = () => undefined + window.localStorage.clear() Object.defineProperty(window, 'hermesDesktop', { configurable: true, @@ -78,9 +78,9 @@ describe('usePreviewRouting', () => { cleanup() $messages.set([]) $previewTarget.set(null) - window.localStorage.clear() - clearSessionPreviewRegistry() vi.restoreAllMocks() + clearSessionPreviewRegistry() + window.localStorage.clear() }) it('opens the active session preview from the registry', async () => { diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx index 66a216d14ae70..3e725b1480d3b 100644 --- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx +++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, render, waitFor } from '@testing-library/react' +import { act, cleanup, render, waitFor } from '@testing-library/react' import type { MutableRefObject } from 'react' import { useEffect, useRef } from 'react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -43,6 +43,18 @@ function sessionInfo(overrides: Partial = {}): SessionInfo { } } +// Wrap render() in act() so the Harness's useEffect (onReady callback + +// internal state from usePromptActions) flushes synchronously instead of +// spilling async state updates outside act(). +async function actRender(ui: React.ReactElement) { + let result: ReturnType + await act(async () => { + result = render(ui) + }) + + return result! +} + interface HarnessHandle { cancelRun: () => Promise restoreToMessage: (messageId: string, target?: { text?: string; userOrdinal?: number | null }) => Promise @@ -125,10 +137,14 @@ function Harness({ useEffect(() => { onReady({ - cancelRun: actions.cancelRun, - restoreToMessage: actions.restoreToMessage, - steerPrompt: actions.steerPrompt, - submitText: actions.submitText + cancelRun: (...args: Parameters) => + act(async () => actions.cancelRun(...args)) as Promise, + restoreToMessage: (...args: Parameters) => + act(async () => actions.restoreToMessage(...args)) as Promise, + steerPrompt: (...args: Parameters) => + act(async () => actions.steerPrompt(...args)) as Promise, + submitText: (...args: Parameters) => + act(async () => actions.submitText(...args)) as Promise }) }, [actions.cancelRun, actions.restoreToMessage, actions.steerPrompt, actions.submitText, onReady]) @@ -153,7 +169,9 @@ describe('usePromptActions /title', () => { ) let handle: HarnessHandle | null = null - render( (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} />) + await actRender( + (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} /> + ) await handle!.submitText('/title New title') @@ -177,7 +195,9 @@ describe('usePromptActions /title', () => { ) let handle: HarnessHandle | null = null - render( (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} />) + await actRender( + (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} /> + ) await handle!.submitText('/title Fresh chat') @@ -195,7 +215,9 @@ describe('usePromptActions /title', () => { const requestGateway = vi.fn(async () => ({ output: 'Title: Old title' }) as never) let handle: HarnessHandle | null = null - render( (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} />) + await actRender( + (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} /> + ) await handle!.submitText('/title') @@ -215,7 +237,9 @@ describe('usePromptActions /title', () => { }) let handle: HarnessHandle | null = null - render( (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} />) + await actRender( + (handle = h)} refreshSessions={refreshSessions} requestGateway={requestGateway} /> + ) await handle!.submitText('/title way too long title') @@ -254,7 +278,7 @@ describe('usePromptActions slash.exec dispatch payloads', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={s => states.push(s)} @@ -304,7 +328,7 @@ describe('usePromptActions slash.exec dispatch payloads', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={s => states.push(s)} @@ -342,7 +366,7 @@ describe('usePromptActions slash.exec dispatch payloads', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -372,7 +396,7 @@ describe('usePromptActions desktop slash pickers', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -392,7 +416,7 @@ describe('usePromptActions desktop slash pickers', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} openMemoryGraph={openMemoryGraph} @@ -425,7 +449,7 @@ describe('usePromptActions desktop slash pickers', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -455,7 +479,7 @@ describe('usePromptActions submit / queue drain semantics', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={s => seeds.push(s)} @@ -488,7 +512,7 @@ describe('usePromptActions submit / queue drain semantics', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} @@ -530,7 +554,7 @@ describe('usePromptActions submit / queue drain semantics', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -574,7 +598,7 @@ describe('usePromptActions submit / queue drain semantics', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={s => seeds.push(s)} @@ -596,7 +620,7 @@ describe('usePromptActions submit / queue drain semantics', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} @@ -622,7 +646,7 @@ describe('usePromptActions steerPrompt', () => { const requestGateway = vi.fn(async () => ({ status: 'queued' }) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -641,7 +665,7 @@ describe('usePromptActions steerPrompt', () => { const requestGateway = vi.fn(async () => ({ status: 'rejected' }) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -654,7 +678,7 @@ describe('usePromptActions steerPrompt', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -665,7 +689,7 @@ describe('usePromptActions steerPrompt', () => { const requestGateway = vi.fn(async () => ({ status: 'queued' }) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -697,7 +721,7 @@ describe('usePromptActions restoreToMessage', () => { let lastState: Record = {} let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={state => (lastState = state)} @@ -732,7 +756,7 @@ describe('usePromptActions restoreToMessage', () => { let lastState: Record = {} let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={state => (lastState = state)} @@ -765,7 +789,7 @@ describe('usePromptActions restoreToMessage', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -793,7 +817,7 @@ describe('usePromptActions restoreToMessage', () => { const requestGateway = vi.fn(async () => ({}) as never) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -808,7 +832,7 @@ describe('usePromptActions restoreToMessage', () => { let lastState: Record = {} let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={state => (lastState = state)} @@ -882,7 +906,7 @@ describe('usePromptActions file attachment sync', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -936,7 +960,7 @@ describe('usePromptActions file attachment sync', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -965,7 +989,7 @@ describe('usePromptActions file attachment sync', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -1025,7 +1049,7 @@ describe('usePromptActions eager-upload races', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) await waitFor(() => expect(handle).not.toBeNull()) @@ -1083,7 +1107,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -1126,7 +1150,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -1159,7 +1183,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} onSeedState={s => states.push(s)} @@ -1189,7 +1213,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -1233,7 +1257,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( (handle = h)} refreshSessions={async () => undefined} @@ -1273,7 +1297,7 @@ describe('usePromptActions sleep/wake session recovery', () => { }) let handle: HarnessHandle | null = null - render( + await actRender( { }) let handle: HarnessHandle | null = null - render( + await actRender( { { id: 'file:devis', kind: 'file', label: 'DEVIS_signed.pdf', path: '/Users/mahmoud/Downloads/DEVIS_signed.pdf' } ]) - render( + await actRender( undefined} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -1622,7 +1646,7 @@ describe('usePromptActions eager attachment upload (drop-time)', () => { $composerAttachments.set([{ id: 'file:x', kind: 'file', label: 'x.pdf', path: '/abs/x.pdf' }]) - render( + await actRender( undefined} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) @@ -1646,7 +1670,7 @@ describe('usePromptActions eager attachment upload (drop-time)', () => { } ]) - render( + await actRender( undefined} refreshSessions={async () => undefined} requestGateway={requestGateway} /> ) diff --git a/apps/desktop/src/app/settings/model-settings.test.tsx b/apps/desktop/src/app/settings/model-settings.test.tsx index 135e9e268f2f8..51c48103388c5 100644 --- a/apps/desktop/src/app/settings/model-settings.test.tsx +++ b/apps/desktop/src/app/settings/model-settings.test.tsx @@ -1,3 +1,4 @@ +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' @@ -32,7 +33,8 @@ vi.mock('@/hermes', () => ({ saveMoaModels: (body: unknown) => saveMoaModels(body), setEnvVar: (key: string, value: string) => setEnvVar(key, value), getHermesConfigRecord: () => getHermesConfigRecord(), - saveHermesConfig: (config: unknown) => saveHermesConfig(config) + saveHermesConfig: (config: unknown) => saveHermesConfig(config), + setApiRequestProfile: () => {} })) vi.mock('@/store/onboarding', () => ({ @@ -71,8 +73,13 @@ afterEach(() => { async function renderModelSettings() { const { ModelSettings } = await import('./model-settings') + const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - return render() + return render( + + + + ) } describe('ModelSettings', () => { diff --git a/apps/desktop/src/app/settings/provider-config-panel.test.tsx b/apps/desktop/src/app/settings/provider-config-panel.test.tsx index 774d45f407935..fa95f9dcd70a9 100644 --- a/apps/desktop/src/app/settings/provider-config-panel.test.tsx +++ b/apps/desktop/src/app/settings/provider-config-panel.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import type { MemoryProviderConfig } from '@/types/hermes' @@ -97,7 +97,12 @@ afterEach(() => { async function renderPanel(provider = 'hindsight') { const { ProviderConfigPanel } = await import('./provider-config-panel') - return render() + let result: ReturnType + await act(async () => { + result = render() + }) + + return result! } describe('ProviderConfigPanel', () => { @@ -115,9 +120,13 @@ describe('ProviderConfigPanel', () => { await renderPanel() expect(await screen.findByLabelText('API URL')).toBeTruthy() - fireEvent.click(screen.getByRole('button', { name: /Hindsight settings/ })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: /Hindsight settings/ })) + }) expect(screen.queryByLabelText('API URL')).toBeNull() - fireEvent.click(screen.getByRole('button', { name: /Hindsight settings/ })) + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: /Hindsight settings/ })) + }) expect(await screen.findByLabelText('API URL')).toBeTruthy() }) @@ -125,9 +134,11 @@ describe('ProviderConfigPanel', () => { await renderPanel() const apiUrl = await screen.findByLabelText('API URL') - fireEvent.change(apiUrl, { target: { value: 'http://localhost:8888' } }) - fireEvent.change(screen.getByLabelText('Bank ID'), { target: { value: 'ben-bank' } }) - fireEvent.click(screen.getByRole('button', { name: 'Save' })) + await act(async () => { + fireEvent.change(apiUrl, { target: { value: 'http://localhost:8888' } }) + fireEvent.change(screen.getByLabelText('Bank ID'), { target: { value: 'ben-bank' } }) + fireEvent.click(screen.getByRole('button', { name: 'Save' })) + }) await waitFor(() => expect(saveMemoryProviderConfig).toHaveBeenCalledWith('hindsight', { diff --git a/apps/desktop/src/app/settings/providers-settings.test.tsx b/apps/desktop/src/app/settings/providers-settings.test.tsx index 8a894e27ab15f..ac63be962ae20 100644 --- a/apps/desktop/src/app/settings/providers-settings.test.tsx +++ b/apps/desktop/src/app/settings/providers-settings.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { atom } from 'nanostores' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -73,8 +73,12 @@ afterEach(() => { async function renderProvidersSettings() { const { ProvidersSettings } = await import('./providers-settings') + let result: ReturnType + await act(async () => { + result = render() + }) - return render() + return result! } describe('ProvidersSettings', () => { @@ -82,7 +86,9 @@ describe('ProvidersSettings', () => { await renderProvidersSettings() const remove = await screen.findByRole('button', { name: 'Remove Nous Portal' }) - fireEvent.click(remove) + await act(async () => { + fireEvent.click(remove) + }) await waitFor(() => expect(disconnectOAuthProvider).toHaveBeenCalledWith('nous')) expect(listOAuthProviders).toHaveBeenCalledTimes(2) @@ -91,7 +97,9 @@ describe('ProvidersSettings', () => { it('keeps provider selection separate from account removal', async () => { await renderProvidersSettings() - fireEvent.click(await screen.findByText('Nous Portal')) + await act(async () => { + fireEvent.click(await screen.findByText('Nous Portal')) + }) expect(startManualProviderOAuth).toHaveBeenCalledWith('nous') expect(disconnectOAuthProvider).not.toHaveBeenCalled() @@ -132,7 +140,9 @@ describe('ProvidersSettings', () => { listOAuthProviders.mockResolvedValue({ providers: [] }) const { ProvidersSettings } = await import('./providers-settings') - render() + await act(async () => { + render() + }) expect(await screen.findByText('WidgetAI')).toBeTruthy() }) @@ -158,14 +168,18 @@ describe('ProvidersSettings', () => { // Typing narrows the list to matching providers only. const search = screen.getByPlaceholderText('Search providers…') - fireEvent.change(search, { target: { value: 'mid' } }) + await act(async () => { + fireEvent.change(search, { target: { value: 'mid' } }) + }) await waitFor(() => expect(screen.queryByText('Acme')).toBeNull()) expect(screen.getByText('Middle')).toBeTruthy() expect(screen.queryByText('Zebra')).toBeNull() // A non-matching query shows the empty-state copy. - fireEvent.change(search, { target: { value: 'nonesuch-xyz' } }) + await act(async () => { + fireEvent.change(search, { target: { value: 'nonesuch-xyz' } }) + }) expect(await screen.findByText('No providers match your search.')).toBeTruthy() }) }) diff --git a/apps/desktop/src/app/shell/model-menu-panel.test.tsx b/apps/desktop/src/app/shell/model-menu-panel.test.tsx index 301a5d2c5b887..7ca78274f343e 100644 --- a/apps/desktop/src/app/shell/model-menu-panel.test.tsx +++ b/apps/desktop/src/app/shell/model-menu-panel.test.tsx @@ -1,5 +1,5 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { cleanup, findByText, fireEvent, render } from '@testing-library/react' +import { cleanup, fireEvent, render } from '@testing-library/react' import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' import { DropdownMenu, DropdownMenuContent } from '@/components/ui/dropdown-menu' @@ -39,7 +39,8 @@ afterEach(() => { function renderPanel(onSelectModel = vi.fn()) { const client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) - render( + + const content = render( @@ -49,15 +50,15 @@ function renderPanel(onSelectModel = vi.fn()) { ) - return onSelectModel + return { onSelectModel, content } } describe('ModelMenuPanel MoA presets', () => { it('selecting a MoA preset switches PERSISTENTLY via onSelectModel (not the one-shot dispatch)', async () => { - const onSelectModel = renderPanel() + const { content, onSelectModel } = renderPanel() // moaOptions is async (useQuery) — wait for the preset row to mount. - const row = await findByText(document.body, 'MoA: BeastMode') + const row = await content.findByText('MoA: BeastMode') fireEvent.click(row) // #54670: must route through the persistent model-switch path @@ -69,30 +70,35 @@ describe('ModelMenuPanel MoA presets', () => { it('shows the check on the preset that matches the current moa selection', async () => { $currentProvider.set('moa') $currentModel.set('BeastMode') - renderPanel() + const { content } = renderPanel() - const row = await findByText(document.body, 'MoA: BeastMode') + const row = await content.findByText('MoA: BeastMode') // The check codicon renders as a sibling within the same row item. const item = row.closest('[role="menuitem"]') ?? row.parentElement expect(item?.querySelector('.codicon-check')).not.toBeNull() }) it('keeps the virtual moa provider out of the main model groups (presets section only)', async () => { - renderPanel() + const { content } = renderPanel() - await findByText(document.body, 'MoA: BeastMode') + await content.findByText('MoA: BeastMode') // The provider group header would read "Mixture of Agents"; the presets // section header reads "MoA presets". Only the latter should exist. + // Radix DropdownMenu portals its content to document.body, so assert + // against the body (not content.container) to see the rendered items. + + // eslint-disable-next-line no-restricted-globals expect(document.body.textContent).toContain('MoA presets') + // eslint-disable-next-line no-restricted-globals expect(document.body.textContent).not.toContain('Mixture of Agents') }) it('renders presets from the catalog even before a session exists', async () => { $activeSessionId.set('') - const onSelectModel = renderPanel() + const { onSelectModel, content } = renderPanel() - const row = await findByText(document.body, 'MoA: BeastMode') + const row = await content.findByText('MoA: BeastMode') fireEvent.click(row) // Pre-session picks are UI state shipped on the next session.create — the diff --git a/apps/desktop/src/app/skills/index.test.tsx b/apps/desktop/src/app/skills/index.test.tsx index fe3e39a72c76d..f4057a4f2b88d 100644 --- a/apps/desktop/src/app/skills/index.test.tsx +++ b/apps/desktop/src/app/skills/index.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { QueryClientProvider } from '@tanstack/react-query' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { MemoryRouter } from 'react-router-dom' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' @@ -48,9 +48,11 @@ function toolset(overrides: Record = {}) { } } -function renderSkills() { - return import('./index').then(({ SkillsView }) => - render( +async function renderSkills() { + const { SkillsView } = await import('./index') + let result: ReturnType + await act(async () => { + result = render( // SkillsView reads skills/toolsets via useQuery, so it needs a provider. @@ -58,7 +60,9 @@ function renderSkills() { ) - ) + }) + + return result! } beforeEach(() => { @@ -83,7 +87,9 @@ describe('SkillsView toolset management', () => { const sw = await screen.findByRole('switch', { name: 'Toggle Web Search toolset' }) expect(sw.getAttribute('aria-checked')).toBe('true') - fireEvent.click(sw) + await act(async () => { + fireEvent.click(sw) + }) await waitFor(() => expect(toggleToolset).toHaveBeenCalledWith('web', false)) }) diff --git a/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx b/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx index cc63d4fbbe381..227f9e63b0251 100644 --- a/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx +++ b/apps/desktop/src/components/assistant-ui/thread/block-direction.test.tsx @@ -25,6 +25,7 @@ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 0) ) vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id)) +vi.stubGlobal('CSS', { escape: (str: string) => str }) Element.prototype.scrollTo = function scrollTo() {} diff --git a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx index 3759f469e2f5d..fb844df0dc2e3 100644 --- a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx +++ b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx @@ -48,6 +48,7 @@ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 0) ) vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id)) +vi.stubGlobal('CSS', { escape: (str: string) => str }) Element.prototype.scrollTo = function scrollTo() {} diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx index 914fc043b1236..3d1e7a69b809a 100644 --- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx +++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit.test.tsx @@ -28,6 +28,7 @@ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => window.setTimeout(() => callback(performance.now()), 0) ) vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id)) +vi.stubGlobal('CSS', { escape: (str: string) => str }) Element.prototype.scrollTo = function scrollTo() {} diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts index 009abcfdf692b..ea253ecadcba3 100644 --- a/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts +++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts @@ -89,7 +89,7 @@ describe('buildToolView browser_navigate title', () => { ) expect(view.status).toBe('error') - expect(view.title).toBe('Failed to open hermes-agent.nousresearch.com') + expect(view.title).toBe('Failed to open hermes-agent.nousresearch.com/docs') }) it('shows opened title on success', () => { @@ -103,7 +103,7 @@ describe('buildToolView browser_navigate title', () => { ) expect(view.status).toBe('success') - expect(view.title).toBe('Opened hermes-agent.nousresearch.com') + expect(view.title).toBe('Opened hermes-agent.nousresearch.com/docs') }) }) diff --git a/apps/desktop/src/components/gateway-connecting-overlay.test.tsx b/apps/desktop/src/components/gateway-connecting-overlay.test.tsx index 0225e8cb22d07..508dfb27f335d 100644 --- a/apps/desktop/src/components/gateway-connecting-overlay.test.tsx +++ b/apps/desktop/src/components/gateway-connecting-overlay.test.tsx @@ -1,4 +1,4 @@ -import { cleanup, render, screen } from '@testing-library/react' +import { act, cleanup, render, screen } from '@testing-library/react' import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { $desktopBoot } from '@/store/boot' @@ -61,7 +61,7 @@ const isRecoveryShown = () => Boolean(screen.queryByText(/use local gateway/i) || screen.queryByText(/retry/i) || screen.queryByText(/sign in/i)) describe('connecting overlay vs recovery surface', () => { - it('hard initial-boot failure surfaces the recovery overlay (the working path)', () => { + it('hard initial-boot failure surfaces the recovery overlay (the working path)', async () => { // failDesktopBoot() ran: error set, gateway never opened. $desktopBoot.set({ ...$desktopBoot.get(), @@ -71,41 +71,50 @@ describe('connecting overlay vs recovery surface', () => { }) setGatewayState('error') - render( - <> - - - - ) + await act(async () => { + render( + <> + + + + ) + }) expect(isRecoveryShown()).toBe(true) // Connecting overlay bows out when boot.error is set. expect(isConnectingShown()).toBe(false) }) - it('post-boot socket drops do not re-cover the app with the initial CONNECTING overlay', () => { + it('post-boot socket drops do not re-cover the app with the initial CONNECTING overlay', async () => { // 1. Initial boot succeeded: gateway opened, boot completed (no error). setGatewayState('open') - const { rerender } = render( - <> - - - - ) + let rerender!: (ui: React.ReactElement) => void + await act(async () => { + const result = render( + <> + + + + ) + + rerender = result.rerender + }) expect(isConnectingShown()).toBe(false) // 2. The remote VPS socket drops (sleep/wake, remote restart, network). // bootCompleted is true, so useGatewayBoot routes this through // scheduleReconnect() — boot.error stays NULL. - setGatewayState('closed') - rerender( - <> - - - - ) + await act(async () => { + setGatewayState('closed') + rerender!( + <> + + + + ) + }) // The initial-boot connecting overlay stays out of the way, so settings and // the composer remain reachable during the reconnect loop. @@ -115,20 +124,23 @@ describe('connecting overlay vs recovery surface', () => { // 3. Reconnect loops against the dead remote: gatewayState bounces closed // → error → closed. Until the escalation path sets boot.error, the app // remains usable instead of modal-blocked. - setGatewayState('error') - rerender( - <> - - - - ) + await act(async () => { + setGatewayState('error') + rerender!( + <> + + + + ) + }) expect($desktopBoot.get().error).toBeNull() expect(isConnectingShown()).toBe(false) expect(isRecoveryShown()).toBe(false) }) - it('soft gateway switch keeps the shell — no fullscreen CONNECTING', () => { + it('soft gateway switch keeps the shell — no fullscreen CONNECTING', async () => { setGatewayState('open') + const { rerender } = render( <> @@ -136,27 +148,29 @@ describe('connecting overlay vs recovery surface', () => { ) - $gatewaySwitching.set(true) - $desktopBoot.set({ - ...$desktopBoot.get(), - running: true, - visible: true, - progress: 4, - error: null + await act(async () => { + $gatewaySwitching.set(true) + $desktopBoot.set({ + ...$desktopBoot.get(), + running: true, + visible: true, + progress: 4, + error: null + }) + setGatewayState('closed') + rerender( + <> + + + + ) }) - setGatewayState('closed') - rerender( - <> - - - - ) expect(isConnectingShown()).toBe(false) expect(isRecoveryShown()).toBe(false) }) - it('FIX: once the prolonged reconnect raises a recoverable boot error, the recovery overlay takes over', () => { + it('FIX: once the prolonged reconnect raises a recoverable boot error, the recovery overlay takes over', async () => { // Mirrors what useGatewayBoot.scheduleReconnect() now does after ~45s of // failed post-boot reconnects: it calls failDesktopBoot(), flipping the UI // from the dead-end CONNECTING overlay to the recovery surface. @@ -168,12 +182,14 @@ describe('connecting overlay vs recovery surface', () => { visible: true }) - render( - <> - - - - ) + await act(async () => { + render( + <> + + + + ) + }) // Escape hatch is now reachable; the connecting overlay bows out. expect(isRecoveryShown()).toBe(true) diff --git a/apps/desktop/src/components/pane-shell/pane-shell.test.tsx b/apps/desktop/src/components/pane-shell/pane-shell.test.tsx index 99f481f054015..0517b08c8ace7 100644 --- a/apps/desktop/src/components/pane-shell/pane-shell.test.tsx +++ b/apps/desktop/src/components/pane-shell/pane-shell.test.tsx @@ -153,7 +153,7 @@ describe('PaneShell composition', () => { const rendered = render( - + files main diff --git a/apps/desktop/src/lib/model-options.test.ts b/apps/desktop/src/lib/model-options.test.ts index a1f6c057ed9d4..65bc180a7f8fc 100644 --- a/apps/desktop/src/lib/model-options.test.ts +++ b/apps/desktop/src/lib/model-options.test.ts @@ -24,7 +24,7 @@ describe('requestModelOptions', () => { await expect(requestModelOptions({ gateway: gateway as never, sessionId: null })).resolves.toBe(gatewayPayload) - expect(gateway.request).toHaveBeenCalledWith('model.options', {}) + expect(gateway.request).toHaveBeenCalledWith('model.options', { explicit_only: true }) expect(getGlobalModelOptions).not.toHaveBeenCalled() }) @@ -36,6 +36,7 @@ describe('requestModelOptions', () => { await requestModelOptions({ gateway: gateway as never, refresh: true, sessionId: 'session-1' }) expect(gateway.request).toHaveBeenCalledWith('model.options', { + explicit_only: true, refresh: true, session_id: 'session-1' }) @@ -44,6 +45,6 @@ describe('requestModelOptions', () => { it('falls back to REST when no gateway is connected', async () => { await requestModelOptions({ refresh: true }) - expect(getGlobalModelOptions).toHaveBeenCalledWith({ refresh: true }) + expect(getGlobalModelOptions).toHaveBeenCalledWith({ explicitOnly: true, refresh: true }) }) }) diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.ts index 17e9964cc8158..0bebec57e6647 100644 --- a/apps/desktop/src/store/onboarding.test.ts +++ b/apps/desktop/src/store/onboarding.test.ts @@ -284,7 +284,7 @@ describe('OAuth onboarding', () => { return { ok: true, status: 'approved' } } - if (path === '/api/model/options') { + if (path.startsWith('/api/model/options')) { return { providers: [ { @@ -357,7 +357,7 @@ describe('OAuth onboarding', () => { expect(calls.some(c => c.path === '/api/model/set')).toBe(true) - const optionsIndex = calls.findIndex(c => c.path === '/api/model/options') + const optionsIndex = calls.findIndex(c => c.path.startsWith('/api/model/options')) const recommendedIndex = calls.findIndex(c => c.path.startsWith('/api/model/recommended-default')) const setIndex = calls.findIndex(c => c.path === '/api/model/set') diff --git a/apps/desktop/src/store/panes.test.ts b/apps/desktop/src/store/panes.test.ts index 6986ae277114c..8ed2fe3723b4a 100644 --- a/apps/desktop/src/store/panes.test.ts +++ b/apps/desktop/src/store/panes.test.ts @@ -97,14 +97,14 @@ describe('panes store', () => { expect(getPaneStateSnapshot('files')?.widthOverride).toBeUndefined() }) - it('width override is in-memory only — not persisted across reloads', () => { + it('width override is NOT in-memory only, and is persisted across reloads', () => { ensurePaneRegistered('files', { open: true }) setPaneWidthOverride('files', 300) const persisted = window.localStorage.getItem(STORAGE_KEY) expect(persisted).not.toBeNull() - expect(JSON.parse(persisted ?? '{}')).toEqual({ files: { open: true } }) + expect(JSON.parse(persisted ?? '{}')).toEqual({ files: { open: true, widthOverride: 300 } }) }) it('open flag is persisted across changes', () => { diff --git a/apps/desktop/src/store/preview.test.ts b/apps/desktop/src/store/preview.test.ts index d5d4807ef530a..d41a7d9e9468e 100644 --- a/apps/desktop/src/store/preview.test.ts +++ b/apps/desktop/src/store/preview.test.ts @@ -48,8 +48,8 @@ describe('preview store', () => { $previewServerRestart.set(null) $activeSessionId.set(null) $selectedStoredSessionId.set(null) - window.localStorage.clear() clearSessionPreviewRegistry() + window.localStorage.clear() }) it('does not notify status subscribers for restart progress text', () => { diff --git a/apps/desktop/vitest.config.ts b/apps/desktop/vitest.config.ts new file mode 100644 index 0000000000000..de633561862a1 --- /dev/null +++ b/apps/desktop/vitest.config.ts @@ -0,0 +1,27 @@ +import type { TestProjectConfiguration } from 'vitest/config'; +import { defineConfig } from 'vitest/config' + +const reactUi: TestProjectConfiguration = { + extends: './vite.config.ts', + test: { + name: 'ui', + environment: 'jsdom', + setupFiles: ['./vitest.setup.ts'], + include: ['src/**/*.test.{ts,tsx}'], + globals: true + } +} + +const electronNative: TestProjectConfiguration = { + test: { + name: 'electron', + environment: 'node', + include: ['electron/**/*.test.ts', 'scripts/**.test.{ts,mjs}'] + } +} + +export default defineConfig({ + test: { + projects: [reactUi, electronNative] + } +}) diff --git a/apps/desktop/vitest.setup.ts b/apps/desktop/vitest.setup.ts new file mode 100644 index 0000000000000..a671ac3ae971d --- /dev/null +++ b/apps/desktop/vitest.setup.ts @@ -0,0 +1,6 @@ +import '@testing-library/react' + +// React 19 + Testing Library 16: opt into the act environment so render(), +// fireEvent(), and findBy* queries automatically flush state updates without +// spurious "not wrapped in act(...)" warnings. +;(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true diff --git a/apps/shared/package.json b/apps/shared/package.json index bd1c10a48a6f9..57b7f776bce94 100644 --- a/apps/shared/package.json +++ b/apps/shared/package.json @@ -8,7 +8,8 @@ }, "types": "./src/index.ts", "scripts": { - "typecheck": "tsc -p . --noEmit" + "typecheck": "tsc -p . --noEmit", + "check": "npm run typecheck" }, "devDependencies": { "typescript": "^6.0.3" diff --git a/package-lock.json b/package-lock.json index 1c25cb2b1dbe7..92b7699b03c2f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19614,7 +19614,8 @@ "wrap-ansi": "^9.0.0" }, "devDependencies": { - "esbuild": "^0.28.1" + "esbuild": "^0.28.1", + "typescript": "^6.0.3" }, "peerDependencies": { "ink-text-input": ">=6.0.0", diff --git a/package.json b/package.json index 9e9448497f681..5eb1e6b637148 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,8 @@ "audit:tui": "npm audit --workspace ui-tui", "audit:fix:root": "npm audit fix --workspaces=false", "audit:fix:web": "npm audit fix --workspace web", - "audit:fix:tui": "npm audit fix --workspace ui-tui" + "audit:fix:tui": "npm audit fix --workspace ui-tui", + "check": "npm run check --ws" }, "repository": { "type": "git", diff --git a/ui-tui/package.json b/ui-tui/package.json index dfdb03b55a03f..7c83ad71e6b36 100644 --- a/ui-tui/package.json +++ b/ui-tui/package.json @@ -4,14 +4,16 @@ "private": true, "type": "module", "scripts": { - "dev": "npm run build --prefix packages/hermes-ink && tsx --watch src/entry.tsx", + "dev": "npm run build:ink && tsx --watch src/entry.tsx", "start": "tsx src/entry.tsx", "build": "node scripts/build.mjs", + "build:ink": "npm run build --prefix packages/hermes-ink", "typecheck": "tsc --noEmit -p tsconfig.json", "lint": "eslint src/ packages/", "lint:fix": "eslint src/ packages/ --fix", "fmt": "prettier --write 'src/**/*.{ts,tsx}' 'packages/**/*.{ts,tsx}'", "fix": "npm run lint:fix && npm run fmt", + "check": "npm run build:ink && npm run typecheck && npm run test", "test": "vitest run", "test:watch": "vitest" }, diff --git a/ui-tui/packages/hermes-ink/package.json b/ui-tui/packages/hermes-ink/package.json index ab6728a7c9fa3..9f4be632bef1f 100644 --- a/ui-tui/packages/hermes-ink/package.json +++ b/ui-tui/packages/hermes-ink/package.json @@ -4,7 +4,9 @@ "private": true, "type": "module", "scripts": { - "build": "esbuild src/entry-exports.ts --bundle --platform=node --format=esm --packages=external --outdir=dist" + "build": "esbuild src/entry-exports.ts --bundle --platform=node --format=esm --packages=external --outdir=dist", + "check": "npm run typecheck", + "typecheck": "tsc -b . --noEmit" }, "sideEffects": true, "main": "./index.js", @@ -49,6 +51,7 @@ "wrap-ansi": "^9.0.0" }, "devDependencies": { - "esbuild": "^0.28.1" + "esbuild": "^0.28.1", + "typescript": "^6.0.3" } } diff --git a/ui-tui/packages/hermes-ink/tsconfig.json b/ui-tui/packages/hermes-ink/tsconfig.json new file mode 100644 index 0000000000000..21601918fe6f6 --- /dev/null +++ b/ui-tui/packages/hermes-ink/tsconfig.json @@ -0,0 +1,3 @@ +{ + "extends": "../../tsconfig.json" +} \ No newline at end of file diff --git a/ui-tui/src/__tests__/cursorDriftRegression.test.ts b/ui-tui/src/__tests__/cursorDriftRegression.test.ts index 3f9082dcefcd4..4ab4e7936395a 100644 --- a/ui-tui/src/__tests__/cursorDriftRegression.test.ts +++ b/ui-tui/src/__tests__/cursorDriftRegression.test.ts @@ -68,7 +68,7 @@ describe('cursor-drift regression — composer cursorLayout matches Ink renderin ).toEqual(expected) } } - }) + }, 30_000) it('keeps cursor on the same row when text exactly fills the terminal width', () => { // wrap-ansi does NOT push exact-fill text onto a phantom next line. diff --git a/ui-tui/src/__tests__/statusRule.test.ts b/ui-tui/src/__tests__/statusRule.test.ts index 6af617a973dc2..9b8224b40789c 100644 --- a/ui-tui/src/__tests__/statusRule.test.ts +++ b/ui-tui/src/__tests__/statusRule.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' -import { busyIndicatorWidth, statusBarSegments, statusRuleWidths } from '../components/appChrome.js' +import { busyIndicatorWidth, StatusBarSegments, statusBarSegments, statusRuleWidths } from '../components/appChrome.js' describe('statusRuleWidths', () => { it('keeps the status rule within the terminal width', () => { @@ -69,8 +69,7 @@ describe('statusBarSegments', () => { voice: true, bg: true, subagents: true, - cost: true - }) + } satisfies StatusBarSegments) }) it('collapses the context bar to a token count on narrow terminals', () => { @@ -79,19 +78,17 @@ describe('statusBarSegments', () => { expect(s.compactCtx).toBe(true) expect(s.bar).toBe(false) expect(s.duration).toBe(false) - expect(s.cost).toBe(false) }) it('sheds tail segments in priority order as the terminal narrows', () => { - // cost is the first to go, the context bar the last of the tail. + // the context bar is the last of the tail to go. const order: (keyof ReturnType)[] = [ 'bar', 'duration', 'compressions', 'voice', 'bg', - 'subagents', - 'cost' + 'subagents' ] let prevCount = Infinity diff --git a/ui-tui/src/__tests__/textInputCursorSourceOfTruth.test.ts b/ui-tui/src/__tests__/textInputCursorSourceOfTruth.test.ts index b52894d158784..e6998d9488ef8 100644 --- a/ui-tui/src/__tests__/textInputCursorSourceOfTruth.test.ts +++ b/ui-tui/src/__tests__/textInputCursorSourceOfTruth.test.ts @@ -1,13 +1,7 @@ -import { readFileSync } from 'node:fs' -import { dirname, join } from 'node:path' -import { fileURLToPath } from 'node:url' - import { describe, expect, it } from 'vitest' -// Locate textInput.tsx relative to this test file so the assertion -// survives moves of the test fixture itself. -const TEXT_INPUT_PATH = join(dirname(fileURLToPath(import.meta.url)), '..', 'components', 'textInput.tsx') -const source = readFileSync(TEXT_INPUT_PATH, 'utf8') +import { cursorLayout } from '../lib/inputMetrics.js' +import { fastAppendEffect, fastBackspaceEffect, resolveCursorLayout } from '../components/textInput.js' // Closes Copilot follow-up on PR #26717: the original cursor-drift // fix bumped Ink's displayCursor / cursorDeclaration on fast-echo, but @@ -18,33 +12,89 @@ const source = readFileSync(TEXT_INPUT_PATH, 'utf8') // bump. The fix is structural: read `curRef.current` (always // up-to-date) when computing the layout, not the `cur` state. // -// This file pins that invariant. Switching back to `cur` state — or -// re-introducing a memo keyed on `cur` that uses `curRef.current` -// inside but stops re-computing on rerender — is a regression and -// should be caught here, not via a flaky integration test that mounts -// Ink + stdin. -describe('textInput cursor-layout source of truth', () => { - it('reads curRef.current (not the cur React state) for cursorLayout', () => { - // The line we care about. We allow whitespace / formatting drift, - // but the call itself must use `curRef.current`. - expect(source).toMatch(/cursorLayout\(\s*display\s*,\s*curRef\.current\s*,\s*columns\s*\)/) +// These tests exercise the real, exported `resolveCursorLayout`, +// `fastBackspaceEffect`, and `fastAppendEffect` helpers that +// `textInput.tsx` calls at its render site and fast-echo call sites — +// no source-text regex, no readFileSync. +describe('resolveCursorLayout', () => { + it('uses curRefCurrent (the fresh ref value), not the stale cur state', () => { + // Simulate the exact bug scenario: `cur` (React state) is stale — + // it still reflects the value before a fast-echo append — while + // `curRef.current` has already advanced past it. + const display = 'hello world' + const staleCur = 5 + const freshCurRefCurrent = 11 + const columns = 80 + + const result = resolveCursorLayout(display, staleCur, freshCurRefCurrent, columns) + const expected = cursorLayout(display, freshCurRefCurrent, columns) + + expect(result).toEqual(expected) + }) + + it('does not match the layout computed from the stale cur value', () => { + const display = 'hello world' + const staleCur = 5 + const freshCurRefCurrent = 11 + const columns = 80 + + const result = resolveCursorLayout(display, staleCur, freshCurRefCurrent, columns) + const staleLayout = cursorLayout(display, staleCur, columns) + + expect(result).not.toEqual(staleLayout) + }) + + it('matches cursorLayout(display, curRefCurrent, columns) even when cur and curRefCurrent agree', () => { + const display = 'hello' + const cur = 5 + const columns = 80 + + expect(resolveCursorLayout(display, cur, cur, columns)).toEqual(cursorLayout(display, cur, columns)) }) +}) + +describe('fastBackspaceEffect', () => { + it('removes the last character, moves the cursor back one, and pairs the write with the advance delta', () => { + const effect = fastBackspaceEffect('hello', 5) + + expect(effect.newValue).toBe('hell') + expect(effect.newCursor).toBe(4) + expect(effect.removed).toBe('o') + // Both the stdout write and the noteCursorAdvance delta live on the + // same returned object — a caller cannot apply `write` without also + // having `advanceDelta` in hand, so the pairing can't silently drift. + expect(effect.write).toBe('\b \b') + expect(effect.advanceDelta).toBe(-1) + }) + + it('handles deleting from the middle of the fast-echo-eligible tail', () => { + const effect = fastBackspaceEffect('abc', 3) + + expect(effect.newValue).toBe('ab') + expect(effect.newCursor).toBe(2) + expect(effect.removed).toBe('c') + expect(effect.write).toBe('\b \b') + expect(effect.advanceDelta).toBe(-1) + }) +}) + +describe('fastAppendEffect', () => { + it('appends the text, advances the cursor by the inserted length, and pairs the write with the advance delta', () => { + const effect = fastAppendEffect('hello', 5, ' world') - it('does not pass the bare `cur` React state into cursorLayout', () => { - // Any `cursorLayout(display, cur, columns)` invocation would - // reintroduce the stale-declaration window. - expect(source).not.toMatch(/cursorLayout\(\s*display\s*,\s*cur\s*,\s*columns\s*\)/) + expect(effect.newValue).toBe('hello world') + expect(effect.newCursor).toBe(11) + // The stdout write is exactly the inserted text, and the + // noteCursorAdvance delta is bundled into the same object. + expect(effect.write).toBe(' world') + expect(effect.advanceDelta).toBe(' world'.length) }) - it('keeps the fast-echo notifier calls paired with the stdout writes', () => { - // Both fast-echo paths must call noteCursorAdvance, otherwise Ink - // never learns about the out-of-band write and drifts again. We - // tolerate explanatory comments in between (the rationale block is - // intentionally long), but the pairing itself must hold. - const backspacePattern = /stdout!\.write\(['"`]\\b \\b['"`]\)[\s\S]{0,1000}?noteCursorAdvance\(-1\)/ - expect(source).toMatch(backspacePattern) + it('advance delta always matches the inserted text length, not a hardcoded value', () => { + const effect = fastAppendEffect('x', 1, 'abc') - const appendPattern = /stdout!\.write\(text\)[\s\S]{0,1000}?noteCursorAdvance\(text\.length\)/ - expect(source).toMatch(appendPattern) + expect(effect.newValue).toBe('xabc') + expect(effect.advanceDelta).toBe(3) + expect(effect.write).toBe('abc') }) }) diff --git a/ui-tui/src/__tests__/virtualHeights.test.ts b/ui-tui/src/__tests__/virtualHeights.test.ts index 9819a7214da96..17cd32fec8d36 100644 --- a/ui-tui/src/__tests__/virtualHeights.test.ts +++ b/ui-tui/src/__tests__/virtualHeights.test.ts @@ -18,10 +18,13 @@ describe('virtual height estimates', () => { }) it('uses compound user prompt width when estimating user message wrapping', () => { - const msg: Msg = { role: 'user', text: 'x'.repeat(21) } + // cols must clear the 20-col body-width floor for both prompts (gutter + + // horizontalReserve=4) so the wider 'Ψ >' prompt actually narrows the + // body enough to wrap an extra line vs the single-cell '❯' prompt. + const msg: Msg = { role: 'user', text: 'x'.repeat(23) } - expect(estimatedMsgHeight(msg, 26, { compact: false, details: false, userPrompt: '❯' })).toBe(3) - expect(estimatedMsgHeight(msg, 26, { compact: false, details: false, userPrompt: 'Ψ >' })).toBe(4) + expect(estimatedMsgHeight(msg, 30, { compact: false, details: false, userPrompt: '❯' })).toBe(3) + expect(estimatedMsgHeight(msg, 30, { compact: false, details: false, userPrompt: 'Ψ >' })).toBe(4) }) it('adds one row for a group-boundary lead gap', () => { diff --git a/ui-tui/src/components/textInput.tsx b/ui-tui/src/components/textInput.tsx index 9cbebd416f48d..9fed82096d25d 100644 --- a/ui-tui/src/components/textInput.tsx +++ b/ui-tui/src/components/textInput.tsx @@ -264,6 +264,81 @@ const ASCII_PRINTABLE_RE = /^[\x20-\x7e]+$/ * length 1 but are still produced by IME compositions and must not be * fast-echoed. */ +/** + * Resolves which cursor position `cursorLayout` should be computed from. + * + * The fast-echo path defers the React `setCur` by 16ms to batch + * re-renders during heavy typing. If an unrelated render flushes this + * component during that window and the layout used the stale `cur` + * React state, the layout effect inside `useDeclaredCursor` would + * publish a stale cursor declaration and clobber the Ink-level bump + * from `noteCursorAdvance(...)` (the cursor-drift regression closed by + * PR #26717's Copilot follow-up). `curRef.current` is always + * up-to-date, so it — never the possibly-stale `cur` state — must be + * the source of truth here. + * + * Extracted as a pure function (rather than inlining `curRef.current` + * directly at the call site) so the invariant is unit-testable without + * mounting Ink/React: construct a scenario where `cur` and + * `curRefCurrent` genuinely diverge and assert the layout matches the + * fresh ref value, not the stale state. + */ +export function resolveCursorLayout(display: string, cur: number, curRefCurrent: number, columns: number) { + void cur // intentionally unused for layout — see doc comment above + + return cursorLayout(display, curRefCurrent, columns) +} + +/** + * Pure computation for the fast-echo backspace bypass: given the + * current value/cursor (already validated by `canFastBackspaceShape`), + * returns what the new value/cursor should be, the exact stdout write + * ("\b \b"), and the delta to report to Ink's `noteCursorAdvance`. + * + * Bundling the write + notifier delta into a single return value means + * the "every fast-echo write must be paired with a matching + * noteCursorAdvance call" invariant is enforced by the return shape + * itself (a caller can't apply `write` without also having + * `advanceDelta` in hand) rather than by two independent call sites + * that happen to sit near each other in source. + */ +export function fastBackspaceEffect( + current: string, + cursor: number +): { advanceDelta: number; newCursor: number; newValue: string; removed: string; write: string } { + const t = prevPos(current, cursor) + const removed = current.slice(t, cursor) + + return { + advanceDelta: -1, + newCursor: t, + newValue: current.slice(0, t) + current.slice(cursor), + removed, + write: '\b \b' + } +} + +/** + * Pure computation for the fast-echo append bypass: given the current + * value/cursor (already validated by `canFastAppendShape`) and the + * inserted text, returns the new value/cursor, the exact stdout write + * (the inserted text itself), and the delta to report to Ink's + * `noteCursorAdvance`. See `fastBackspaceEffect` for why write + delta + * are bundled into one return value. + */ +export function fastAppendEffect( + current: string, + cursor: number, + text: string +): { advanceDelta: number; newCursor: number; newValue: string; write: string } { + return { + advanceDelta: text.length, + newCursor: cursor + text.length, + newValue: current.slice(0, cursor) + text + current.slice(cursor), + write: text + } +} + export function canFastAppendShape( current: string, cursor: number, @@ -517,7 +592,7 @@ export function TextInput({ // for layout. The cursorLayout call is cheap (one wrap-text pass // over a single-line string in the common case), so dropping useMemo // is fine. - const layout = cursorLayout(display, curRef.current, columns) + const layout = resolveCursorLayout(display, cur, curRef.current, columns) const boxRef = useDeclaredCursor({ line: layout.line, @@ -1080,16 +1155,16 @@ export function TextInput({ v = v.slice(0, t) + v.slice(c) c = t } else if (canFastBackspace(v, c)) { - const t = prevPos(v, c) - v = v.slice(0, t) + v.slice(c) - c = t - stdout!.write('\b \b') + const effect = fastBackspaceEffect(v, c) + v = effect.newValue + c = effect.newCursor + stdout!.write(effect.write) // The "\b \b" sequence ends with the cursor one column to the // LEFT of where Ink last parked it. Tell Ink so its `displayCursor` // (and log-update's relative-move basis on the next frame) stays // in sync — otherwise the cursor parks one cell to the right of // the caret on the next unrelated re-render. - noteCursorAdvance(-1) + noteCursorAdvance(effect.advanceDelta) commit(v, c, true, false, false, Math.max(0, lineWidthRef.current - 1)) return @@ -1184,12 +1259,15 @@ export function TextInput({ c = inserted.cursor } else { const simpleAppend = canFastAppend(v, c, text) + const preInsertValue = v + const preInsertCursor = c v = inserted.value c = inserted.cursor if (simpleAppend) { - stdout!.write(text) + const effect = fastAppendEffect(preInsertValue, preInsertCursor, text) + stdout!.write(effect.write) // ASCII-printable text advances the physical cursor by exactly // text.length cells (canFastAppendShape rejects non-ASCII, // wide chars, newlines). Notify Ink so the cached displayCursor @@ -1197,7 +1275,7 @@ export function TextInput({ // any unrelated re-render that happens before the 16ms // setCur/setParent flush parks the cursor text.length cells // too far right (#cursor-drift). - noteCursorAdvance(text.length) + noteCursorAdvance(effect.advanceDelta) commit(v, c, true, false, false, lineWidthRef.current + stringWidth(text)) return diff --git a/web/package.json b/web/package.json index d211f68c2d772..8dfe84074a099 100644 --- a/web/package.json +++ b/web/package.json @@ -9,7 +9,8 @@ "lint": "eslint .", "preview": "vite preview", "typecheck": "tsc -p . --noEmit", - "test": "vitest run" + "test": "vitest run", + "check": "npm run typecheck && npm run test" }, "dependencies": { "@hermes/shared": "file:../apps/shared",