Merge origin/main into model-catalog-probe

This commit is contained in:
Brennan Benson
2026-11-13 02:19:27 -08:00
452 changed files with 5193 additions and 6938 deletions
+14
View File
@@ -5,6 +5,9 @@ const {
MACOS_FOLDER_USAGE_DESCRIPTIONS,
applyMacHelperFolderUsageDescriptions
} = require('./scripts/desktop-distribution/macos/macos-folder-usage-descriptions.cjs')
const {
giveMacExecutableUniqueUuid
} = require('./scripts/desktop-distribution/macos/macos-executable-uuid.cjs')
const electronBuilderNativeRebuild = require('./scripts/desktop-distribution/runtime-verification/electron-builder-native-rebuild.cjs')
const {
assertPackagedDaemonEntryExists,
@@ -426,6 +429,17 @@ module.exports = {
join(context.appOutDir, `${context.packager.appInfo.productFilename}.app`),
context.packager.appInfo.productFilename
)
// Before signing, so the signature seals the rewritten executable.
giveMacExecutableUniqueUuid(
join(
context.appOutDir,
`${context.packager.appInfo.productFilename}.app`,
'Contents',
'MacOS',
context.packager.appInfo.productFilename
),
context.packager.appInfo.id
)
const architecture = macSliceArch(context.arch, 'local-build compatibility')
const schedulingAddon = buildMacShipItScheduling(resourcesDir, architecture)
await signMacStandaloneHelper(schedulingAddon, 'ShipIt scheduling', context.packager)
+6 -6
View File
@@ -64,12 +64,12 @@
1 src/renderer/src/components/linear-item-drawer-edit-section.tsx
1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx
1 src/renderer/src/components/native-chat/media/visuals/NativeChatVisualFrame.tsx
1 src/renderer/src/components/new-workspace/use-jira-source-connection.ts
7 src/renderer/src/components/new-workspace/use-linear-source-connection.ts
1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts
1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts
6 src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts
1 src/renderer/src/components/new-workspace/use-work-item-source-search.ts
1 src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts
7 src/renderer/src/components/new-workspace/source-search/use-linear-source-connection.ts
1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts
1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts
6 src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts
1 src/renderer/src/components/new-workspace/source-search/use-work-item-source-search.ts
1 src/renderer/src/components/provider-accounts/provider-account-scope.ts
2 src/renderer/src/components/right-sidebar/checks-panel/review-actions/checks-panel-hosted-review-click-routing.ts
1 src/renderer/src/components/right-sidebar/hosted-review/creation/use-create-pull-request-base-ref-discovery.ts
+1 -1
View File
@@ -6,4 +6,4 @@
1 src/preload/api/app-bridge.ts
1 src/preload/api/native-chat-bridge.ts
1 src/preload/api/settings-bridge.ts
1 src/preload/native-chat-visual-guest-theme.ts
1 src/preload/native-chat/native-chat-visual-guest-theme.ts
+6 -6
View File
@@ -260,12 +260,12 @@
2 src/renderer/src/components/native-chat/viewport/virtualization/NativeChatTranscriptItems.tsx
1 src/renderer/src/components/native-chat/viewport/virtualization/use-native-chat-transcript-window.ts
1 src/renderer/src/components/network/CustomAddressDialog.tsx
1 src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.tsx
1 src/renderer/src/components/new-workspace/RunTargetCombobox.tsx
3 src/renderer/src/components/new-workspace/SetProjectLocationDialog.tsx
2 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-actions.ts
1 src/renderer/src/components/new-workspace/use-smart-workspace-name-field-controller.ts
1 src/renderer/src/components/new-workspace/use-smart-workspace-secondary-searches.ts
1 src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.tsx
1 src/renderer/src/components/new-workspace/run-target/RunTargetCombobox.tsx
3 src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.tsx
2 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-actions.ts
1 src/renderer/src/components/new-workspace/name-field/use-smart-workspace-name-field-controller.ts
1 src/renderer/src/components/new-workspace/source-search/use-smart-workspace-secondary-searches.ts
2 src/renderer/src/components/onboarding/AgentStep.tsx
2 src/renderer/src/components/onboarding/NotificationStep.tsx
8 src/renderer/src/components/onboarding/OnboardingFlow.tsx
+2 -2
View File
@@ -7,8 +7,8 @@ src/renderer/src/components/feature-wall/setup/FeatureWallSetupChecklist.tsx
src/renderer/src/components/feature-wall/setup/integrations/use-integration-connection-status.ts
src/renderer/src/components/integrations/task-trackers/jira-integration-card.tsx
src/renderer/src/components/integrations/task-trackers/linear-integration-card.tsx
src/renderer/src/components/new-workspace/use-jira-source-connection.ts
src/renderer/src/components/new-workspace/use-work-item-source-foundation.ts
src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.ts
src/renderer/src/components/new-workspace/source-search/use-work-item-source-foundation.ts
src/renderer/src/components/settings/skills/linear/LinearAgentSkillPane.tsx
src/renderer/src/components/settings/tasks/use-task-source-provider-readiness.ts
src/renderer/src/components/sidebar/workspace-card/details/use-worktree-card-review-details.ts
File diff suppressed because one or more lines are too long
@@ -770,7 +770,6 @@
"src/main/automations/automation-dispatch-host-fence.test.ts": 2592,
"src/main/automations/automation-owner-fencing.test.ts": 2028,
"src/main/automations/automation-run-terminal-surface.test.ts": 4180,
"src/main/automations/automation-skip-coalescing.test.ts": 2577,
"src/main/automations/ownership/automation-ssh-readoption-migration.test.ts": 59,
"src/main/automations/automation-update-host-retarget.test.ts": 1842,
@@ -945,7 +944,6 @@
"src/main/browser/extensions/api/browser-extension-api-namespaces.test.ts": 832,
"src/main/browser/extensions/installation/browser-extension-archive.test.ts": 72,
"src/main/browser/extensions/actions/browser-extension-commands.test.ts": 52,
"src/main/browser/extensions/api-runtime/browser-extension-content-script-persistence.test.ts": 313,
"src/main/browser/extensions/context-menus/browser-extension-context-menu-host.test.ts": 68,
"src/main/browser/extensions/context-menus/browser-extension-context-menu-model.test.ts": 57,
"src/main/browser/extensions/installation/browser-extension-crx.test.ts": 214,
@@ -2642,7 +2640,6 @@
"src/main/plugins/catalog/plugin-update-review-notices.test.ts": 175,
"src/main/plugins/contributions/plugin-content-pack-registry.test.ts": 589,
"src/main/plugins/contributions/plugin-icon-theme-registry.test.ts": 268,
"src/main/plugins/contributions/plugin-language-pack-registry.test.ts": 587,
"src/main/plugins/contributions/plugin-syntax-registry.test.ts": 221,
"src/main/plugins/contributions/plugin-theme-registries.test.ts": 250,
"src/main/plugins/hooks/plugin-agent-hook-sites.test.ts": 279,
@@ -3904,7 +3901,6 @@
"src/main/text-generation/requests/jira-issue-summary-requests.test.ts": 276,
"src/main/text-generation/failures/kimi-generation-failure.test.ts": 151,
"src/main/text-generation/execution/source-control-agent-cli-path.test.ts": 615,
"src/main/text-generation/execution/source-control-agent-launch.test.ts": 1879,
"src/main/text-generation/execution/source-control-local-process.test.ts": 1834,
"src/main/text-generation/prompts/source-control-omp-prompt-file.test.ts": 6676,
"src/main/text-generation/execution/source-control-wsl-launch.test.ts": 482,
@@ -4127,32 +4123,25 @@
"src/packages/process-host/src/windows-tree-kill.test.ts": 81,
"src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55,
"src/preload/api/notification-sound-playback.test.ts": 64,
"src/preload/api/platform-bridge.test.ts": 48,
"src/preload/app-restart-checkpoint-routing.test.ts": 2028,
"src/preload/browser-client-page-renderer-requests.test.ts": 154,
"src/preload/browser-extension-content-script-relay.test.ts": 65,
"src/preload/browser-extension-document-targets.test.ts": 75,
"src/preload/browser-extension-inert-apis.test.ts": 50,
"src/preload/browser-extension-main-world.test.ts": 81,
"src/preload/browser-extension-native-messaging.test.ts": 70,
"src/preload/browser-extension-storage-relay.test.ts": 104,
"src/preload/browser-extension-storage-sync.test.ts": 108,
"src/preload/browser-extension-web-store-main-world.test.ts": 166,
"src/preload/browser-extension-web-store-wording.test.ts": 194,
"src/preload/browser-find-subscriptions.test.ts": 66,
"src/preload/renderer/restart/app-restart-checkpoint-routing.test.ts": 2028,
"src/preload/renderer/browser-pages/browser-client-page-renderer-requests.test.ts": 154,
"src/preload/browser/extensions/messaging/browser-extension-content-script-relay.test.ts": 65,
"src/preload/browser/extensions/documents/browser-extension-document-targets.test.ts": 75,
"src/preload/browser/extensions/api/browser-extension-inert-apis.test.ts": 50,
"src/preload/browser/extensions/api/browser-extension-main-world.test.ts": 81,
"src/preload/browser/extensions/storage/browser-extension-storage-relay.test.ts": 104,
"src/preload/browser/extensions/storage/browser-extension-storage-sync.test.ts": 108,
"src/preload/browser/extensions/web-store/browser-extension-web-store-main-world.test.ts": 166,
"src/preload/renderer/browser-pages/browser-find-subscriptions.test.ts": 66,
"src/preload/browser-window-close.test.ts": 98,
"src/preload/close-active-tab-payload-admission.test.ts": 48,
"src/preload/renderer/window-commands/close-active-tab-payload-admission.test.ts": 48,
"src/preload/doc-preview-link-interception.test.ts": 234,
"src/preload/gitlab-work-item-details.test.ts": 49,
"src/preload/opencode-go-credentials.test.ts": 45,
"src/preload/plugin-frame-guest-render-lane.test.ts": 47,
"src/preload/plugin-frame-guest.test.ts": 287,
"src/preload/renderer-heap-statistics-reader.test.ts": 50,
"src/preload/renderer-process-memory-reader.test.ts": 66,
"src/preload/renderer-restart-wiring.test.ts": 96,
"src/preload/ssh-authority-forwarding.test.ts": 1111,
"src/preload/updater-package-recovery.test.ts": 1102,
"src/preload/usage-provider-api.test.ts": 46,
"src/preload/plugins/frames/plugin-frame-guest-render-lane.test.ts": 47,
"src/preload/plugins/frames/plugin-frame-guest.test.ts": 287,
"src/preload/renderer/diagnostics/renderer-heap-statistics-reader.test.ts": 50,
"src/preload/renderer/diagnostics/renderer-process-memory-reader.test.ts": 66,
"src/preload/renderer/restart/renderer-restart-wiring.test.ts": 96,
"src/preload/api/ssh-authority-forwarding.test.ts": 1111,
"src/renderer/src/app-shell/shutdown-checkpoint-persist.test.ts": 65,
"src/renderer/src/app-shell/use-profile-state-save-delay-notice.sonner.test.tsx": 355,
"src/renderer/src/app-shell/use-profile-state-save-delay-notice.test.tsx": 293,
@@ -4755,28 +4744,24 @@
"src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.clear-send.test.tsx": 2804,
"src/renderer/src/components/native-chat/pane/actions/use-structured-native-chat-submit-reveal.test.ts": 2304,
"src/renderer/src/components/network/CustomAddressDialog.test.tsx": 568,
"src/renderer/src/components/new-workspace/ComposerParentWorktreePicker.test.tsx": 870,
"src/renderer/src/components/new-workspace/DirectWorkItemSetupDialog.test.tsx": 5296,
"src/renderer/src/components/new-workspace/NewWorkspaceComposerNameSection.test.tsx": 2493,
"src/renderer/src/components/new-workspace/ProjectCombobox.dialog-handoff.test.tsx": 1043,
"src/renderer/src/components/new-workspace/branch-selection/ComposerParentWorktreePicker.test.tsx": 870,
"src/renderer/src/components/new-workspace/RunTargetCombobox.host-identity.test.tsx": 856,
"src/renderer/src/components/new-workspace/SetProjectLocationDialog.host-identity.test.tsx": 1094,
"src/renderer/src/components/new-workspace/SetProjectLocationDialog.test.tsx": 1387,
"src/renderer/src/components/new-workspace/project-location/SetProjectLocationDialog.test.tsx": 1387,
"src/renderer/src/components/new-workspace/SmartWorkspaceNameField-repo-slug-routing.test.ts": 342,
"src/renderer/src/components/new-workspace/smart-workspace-github-direct-link.test.ts": 347,
"src/renderer/src/components/new-workspace/smart-workspace-source-results.test.ts": 136,
"src/renderer/src/components/new-workspace/use-jira-source-connection.test.tsx": 278,
"src/renderer/src/components/new-workspace/use-jira-url-source.test.tsx": 419,
"src/renderer/src/components/new-workspace/source-search/smart-workspace-github-direct-link.test.ts": 347,
"src/shared/new-workspace/smart-workspace-source-results.test.ts": 136,
"src/renderer/src/components/new-workspace/source-search/use-jira-source-connection.test.tsx": 278,
"src/renderer/src/components/new-workspace/source-search/use-jira-url-source.test.tsx": 419,
"src/renderer/src/components/new-workspace/use-linear-source-connection.test.tsx": 1335,
"src/renderer/src/components/new-workspace/use-recent-project-ids.test.ts": 1730,
"src/renderer/src/components/new-workspace/use-smart-workspace-name-field-foundation.source.test.tsx": 2290,
"src/renderer/src/components/new-workspace/project-selection/use-recent-project-ids.test.ts": 1730,
"src/renderer/src/components/new-workspace/source-search/use-smart-workspace-name-field-foundation.source.test.tsx": 2290,
"src/renderer/src/components/new-workspace/work-item-source-selection.test.ts": 1736,
"src/renderer/src/components/onboarding/OnboardingLanguageLoading.test.tsx": 2167,
"src/renderer/src/components/pet/pet-blob-cache.test.ts": 64,
"src/renderer/src/components/plain-ssh-terminal/PlainSshTerminalPanels.test.tsx": 2510,
"src/renderer/src/components/plugins/declarative/PluginDeclarativeView.test.tsx": 2804,
"src/renderer/src/components/plugins/dialogs/PluginUpdateAllDialog.test.tsx": 2313,
"src/renderer/src/components/plugins/list/PluginManager.test.tsx": 3449,
"src/renderer/src/components/plugins/list/plugin-list-entries.test.ts": 231,
"src/renderer/src/components/plugins/page/PluginAddsSection.test.tsx": 2043,
"src/renderer/src/components/plugins/page/PluginCommandReplacementRow.test.tsx": 1926,
@@ -4784,7 +4769,6 @@
"src/renderer/src/components/plugins/page/PluginSettingsSection.test.tsx": 572,
"src/renderer/src/components/plugins/state/use-plugin-contribution-source.test.tsx": 1935,
"src/renderer/src/components/plugins/state/use-plugin-install-link.test.tsx": 518,
"src/renderer/src/components/plugins/state/use-plugin-page-navigation.test.tsx": 480,
"src/renderer/src/components/plugins/state/use-plugin-review-queue.test.tsx": 389,
"src/renderer/src/components/plugins/view/plugin-view-acts.test.tsx": 3241,
"src/renderer/src/components/plugins/view/plugin-view-data-acts.test.tsx": 3002,
@@ -5395,10 +5379,7 @@
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal-late-settlement.test.ts": 1880,
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-background-removal.test.ts": 283,
"src/renderer/src/components/workspace-cleanup/candidate-evidence/workspace-cleanup-host-index.test.ts": 341,
"src/renderer/src/components/workspace-cleanup/query/workspace-cleanup-facet-sort.test.ts": 264,
"src/renderer/src/components/workspace-cleanup/candidate-list/workspace-cleanup-flat-list.test.tsx": 2594,
"src/renderer/src/components/workspace-cleanup/removal/workspace-cleanup-removal-candidates.test.ts": 206,
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-settlement.test.ts": 203,
"src/renderer/src/components/workspace-cleanup/removal/settlement/workspace-cleanup-removal-timeout-recovery.test.ts": 1817,
"src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerButton.test.tsx": 1086,
"src/renderer/src/components/workspace-emoji/WorkspaceEmojiPickerPanel.test.tsx": 763,
@@ -6519,7 +6500,6 @@
"src/shared/plugins/contributions/plugin-content-pack-contributions.test.ts": 227,
"src/shared/plugins/contributions/plugin-custom-editor-contribution.test.ts": 238,
"src/shared/plugins/declarative/plugin-declarative-catalog-rich.test.ts": 147,
"src/shared/plugins/declarative/plugin-declarative-example.test.ts": 198,
"src/shared/plugins/declarative/plugin-declarative-tree.test.ts": 168,
"src/shared/plugins/declarative/runtime/declarative-act-snapshot.test.ts": 64,
"src/shared/plugins/declarative/runtime/declarative-error-location.test.ts": 63,
@@ -1,6 +1,7 @@
import { execFileSync } from 'node:child_process'
import { createRequire } from 'node:module'
import { join, resolve } from 'node:path'
import { basename, join, resolve } from 'node:path'
import { assertMacExecutableUuid } from './macos-executable-uuid.cjs'
const ARCHITECTURES = [1, 3] // electron-builder: x64, arm64.
@@ -138,6 +139,10 @@ export async function main(args = process.argv.slice(2)) {
verify: (appPath) => {
execFileSync('codesign', ['--verify', '--deep', '--strict', appPath], { stdio: 'inherit' })
execFileSync('xcrun', ['stapler', 'validate', appPath], { stdio: 'inherit' })
assertMacExecutableUuid(
join(appPath, 'Contents', 'MacOS', basename(appPath, '.app')),
config.appId
)
},
targets: new Map([
[
@@ -0,0 +1,115 @@
// macOS Local Network privacy maps a process to its app by executable UUID; stock Electron's is shared by every app shipping that build (TN3179).
const { execFileSync } = require('node:child_process')
const { createHash } = require('node:crypto')
const { copyFileSync, mkdtempSync, readFileSync, rmSync, writeFileSync } = require('node:fs')
const { tmpdir } = require('node:os')
const { basename, join } = require('node:path')
const MH_MAGIC = 0xfeedface
const MH_MAGIC_64 = 0xfeedfacf
const FAT_MAGIC = 0xcafebabe
const FAT_MAGIC_64 = 0xcafebabf
const LC_UUID = 0x1b
function formatUuid(bytes) {
const hex = Buffer.from(bytes).toString('hex').toUpperCase()
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}
// Stable per app, executable and CPU so releases keep one identity, as the stock UUID did within an Electron version.
function deriveExecutableUuid(appId, executableName, cpuType) {
const uuid = createHash('sha256')
.update(`${appId}\0${executableName}\0${cpuType}`)
.digest()
.subarray(0, 16)
uuid[6] = (uuid[6] & 0x0f) | 0x80
uuid[8] = (uuid[8] & 0x3f) | 0x80
return uuid
}
function sliceOffsets(buffer) {
const magic = buffer.readUInt32BE(0)
if (magic !== FAT_MAGIC && magic !== FAT_MAGIC_64) {
return [0]
}
const is64 = magic === FAT_MAGIC_64
const count = buffer.readUInt32BE(4)
const offsets = []
for (let i = 0; i < count; i++) {
const entry = 8 + i * (is64 ? 32 : 20)
offsets.push(is64 ? Number(buffer.readBigUInt64BE(entry + 8)) : buffer.readUInt32BE(entry + 8))
}
return offsets
}
/** Where each slice's LC_UUID payload sits. */
function machOUuidSlots(buffer) {
return sliceOffsets(buffer).map((offset) => {
const magic = buffer.readUInt32LE(offset)
if (magic !== MH_MAGIC && magic !== MH_MAGIC_64) {
throw new Error(
`Unsupported Mach-O slice at offset ${offset} (magic 0x${magic.toString(16)})`
)
}
const cpuType = buffer.readUInt32LE(offset + 4)
const commandCount = buffer.readUInt32LE(offset + 16)
let command = offset + (magic === MH_MAGIC_64 ? 32 : 28)
for (let i = 0; i < commandCount; i++) {
if (buffer.readUInt32LE(command) === LC_UUID) {
return { cpuType, uuidOffset: command + 8 }
}
command += buffer.readUInt32LE(command + 4)
}
throw new Error(`Mach-O slice for CPU type ${cpuType} has no LC_UUID`)
})
}
/** Rewrites LC_UUID in every slice of `buffer` in place. */
function rewriteMachOUuids(buffer, appId, executableName) {
return machOUuidSlots(buffer).map(({ cpuType, uuidOffset }) => {
const before = formatUuid(buffer.subarray(uuidOffset, uuidOffset + 16))
const next = deriveExecutableUuid(appId, executableName, cpuType)
next.copy(buffer, uuidOffset)
return { cpuType, before, after: formatUuid(next) }
})
}
/** Gives the executable its own UUID, then re-signs it ad hoc; real signing replaces that later. */
function giveMacExecutableUniqueUuid(executable, appId) {
const name = basename(executable)
const buffer = readFileSync(executable)
const changes = rewriteMachOUuids(buffer, appId, name)
// The edit breaks Electron's linker ad hoc signature and arm64 kills unsigned code, but identity-less builds skip app signing.
// Signed outside the bundle: in place, codesign would treat it as the bundle and require its unsigned siblings be signed.
const staging = mkdtempSync(join(tmpdir(), 'orca-executable-uuid-'))
try {
const staged = join(staging, name)
writeFileSync(staged, buffer, { mode: 0o755 })
execFileSync('codesign', ['--force', '--sign', '-', '--identifier', appId, staged], {
stdio: 'inherit'
})
copyFileSync(staged, executable)
} finally {
rmSync(staging, { recursive: true, force: true })
}
for (const { cpuType, before, after } of changes) {
console.log(`[macos-executable-uuid] ${name} cpu ${cpuType}: ${before} -> ${after}`)
}
}
/** Fails when a shipped executable lost its own UUID, e.g. the hook was skipped or signing rewrote it. */
function assertMacExecutableUuid(executable, appId) {
const name = basename(executable)
const buffer = readFileSync(executable)
for (const { cpuType, uuidOffset } of machOUuidSlots(buffer)) {
const actual = formatUuid(buffer.subarray(uuidOffset, uuidOffset + 16))
const expected = formatUuid(deriveExecutableUuid(appId, name, cpuType))
if (actual !== expected) {
throw new Error(
`[macos-executable-uuid] ${executable} cpu ${cpuType} has UUID ${actual}, expected ${expected}`
)
}
}
}
module.exports = { assertMacExecutableUuid, giveMacExecutableUniqueUuid, rewriteMachOUuids }
@@ -0,0 +1,99 @@
import { execFileSync } from 'node:child_process'
import { copyFileSync, mkdtempSync, rmSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
const require = createRequire(import.meta.url)
const {
assertMacExecutableUuid,
giveMacExecutableUniqueUuid,
rewriteMachOUuids
} = require('./macos-executable-uuid.cjs')
const ARM64 = 0x0100000c
const X86_64 = 0x01000007
const STOCK_UUID = Buffer.from('4C4C44C055553144A1E0C291B44FDBE3', 'hex')
function thinSlice(cpuType) {
const header = Buffer.alloc(32)
header.writeUInt32LE(0xfeedfacf, 0)
header.writeUInt32LE(cpuType, 4)
header.writeUInt32LE(2, 12)
header.writeUInt32LE(2, 16)
header.writeUInt32LE(16 + 24, 20)
const other = Buffer.alloc(16, 0xaa)
other.writeUInt32LE(0x19, 0)
other.writeUInt32LE(16, 4)
const uuid = Buffer.alloc(24)
uuid.writeUInt32LE(0x1b, 0)
uuid.writeUInt32LE(24, 4)
STOCK_UUID.copy(uuid, 8)
return Buffer.concat([header, other, uuid, Buffer.alloc(8, 0xbb)])
}
function fatBinary(slices) {
const table = Buffer.alloc(8 + slices.length * 20)
table.writeUInt32BE(0xcafebabe, 0)
table.writeUInt32BE(slices.length, 4)
const parts = [table]
let offset = 4096
slices.forEach((slice, i) => {
table.writeUInt32BE(slice.readUInt32LE(4), 8 + i * 20)
table.writeUInt32BE(offset, 8 + i * 20 + 8)
table.writeUInt32BE(slice.length, 8 + i * 20 + 12)
const end = parts.reduce((n, p) => n + p.length, 0)
parts.push(Buffer.alloc(offset - end), slice)
offset += 4096
})
return Buffer.concat(parts)
}
const uuidAt = (buffer, offset) => buffer.subarray(offset, offset + 16).toString('hex')
describe('rewriteMachOUuids', () => {
it('replaces the stock UUID of a thin executable and nothing else', () => {
const original = thinSlice(ARM64)
const rewritten = Buffer.from(original)
rewriteMachOUuids(rewritten, 'com.stablyai.orca', 'Orca')
expect(uuidAt(rewritten, 56)).toBe('e64304103b228bd69677b18884034a30')
expect(Buffer.concat([rewritten.subarray(0, 56), rewritten.subarray(72)])).toEqual(
Buffer.concat([original.subarray(0, 56), original.subarray(72)])
)
})
it('gives every slice of a universal executable its own stable UUID', () => {
const binary = fatBinary([thinSlice(X86_64), thinSlice(ARM64)])
rewriteMachOUuids(binary, 'com.stablyai.orca', 'Orca')
rewriteMachOUuids(binary, 'com.stablyai.orca', 'Orca')
expect(uuidAt(binary, 4096 + 56)).toBe('016ee6813dc381c7a6da12dc23b89dd9')
expect(uuidAt(binary, 8192 + 56)).toBe('e64304103b228bd69677b18884034a30')
})
it('refuses an executable without LC_UUID', () => {
const slice = thinSlice(ARM64)
slice.writeUInt32LE(0x1a, 48)
expect(() => rewriteMachOUuids(slice, 'com.stablyai.orca', 'Orca')).toThrow('has no LC_UUID')
})
})
describe.runIf(process.platform === 'darwin')('giveMacExecutableUniqueUuid', () => {
it('leaves a signed, runnable universal executable that passes the release check', () => {
const dir = mkdtempSync(join(tmpdir(), 'orca-exe-uuid-'))
try {
const executable = join(dir, 'Orca')
// A real platform-signed fat binary: rewriting it without re-signing gets it killed at exec.
copyFileSync('/usr/bin/true', executable)
expect(() => assertMacExecutableUuid(executable, 'com.stablyai.orca')).toThrow(
'expected 016EE681-3DC3-81C7-A6DA-12DC23B89DD9'
)
giveMacExecutableUniqueUuid(executable, 'com.stablyai.orca')
execFileSync(executable)
execFileSync('codesign', ['--verify', '--strict', executable])
assertMacExecutableUuid(executable, 'com.stablyai.orca')
} finally {
rmSync(dir, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,115 @@
// Regenerates src/shared/dictation-english-words.ts, the common-word filter dictation's near-miss matching
// checks before spelling a word as a dictionary term. Run: node config/scripts/dictation/build-dictation-english-words.mjs
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { wordFilterSlots } from '../../../src/shared/dictation-word-filter.ts'
const SOURCES = {
scowl: [
'https://downloads.sourceforge.net/project/wordlist/SCOWL/2020.12.07/scowl-2020.12.07.tar.gz',
'5587667caa20c4891390c2d42dbb4d5c4c3f41bee77af1457ece3ba23fb859cc'
],
femaleFirst: [
'https://www2.census.gov/topics/genealogy/1990surnames/dist.female.first',
'bd2f310fc4e5d5e5ea122c9d4342c9821145823118eb20db1647f305ec77b358'
],
maleFirst: [
'https://www2.census.gov/topics/genealogy/1990surnames/dist.male.first',
'0a5078ef6effe3b483d15b0f7f95047662126c9bfb624ecd5e5b978fc0f2470b'
],
last: [
'https://www2.census.gov/topics/genealogy/1990surnames/dist.all.last',
'b0e2b3743ccbad641ca48b344c24cdebcd1d9a1f76dc6dbf05986f2919f0b4e1'
]
}
// SCOWL sizes up to 60: everyday words plus the rarer ones ("bezel", "aslant") a term could sound like.
const SCOWL_MAX_SIZE = 60
const LAST_NAMES = 1000
const FALSE_POSITIVE_RATE = 0.02
// Matching never looks up words shorter than this.
const MIN_WORD_LENGTH = 3
const OUT = 'src/shared/dictation-english-words.ts'
async function download([url, sha256]) {
const response = await fetch(url)
if (!response.ok) {
throw new Error(`${url}: HTTP ${response.status}`)
}
const bytes = Buffer.from(await response.arrayBuffer())
const actual = createHash('sha256').update(bytes).digest('hex')
if (actual !== sha256) {
throw new Error(`${url}: sha256 ${actual}, expected ${sha256}`)
}
return bytes
}
const work = mkdtempSync(join(tmpdir(), 'dictation-english-words-'))
try {
const words = new Set()
// Contractions add their stems ("doesn" of "doesn't"), since dictated text splits words at apostrophes.
const add = (entry) => {
for (const part of entry.split("'")) {
if (/^[A-Za-z]+$/.test(part) && part.length >= MIN_WORD_LENGTH) {
words.add(part.toLowerCase())
}
}
}
writeFileSync(join(work, 'scowl.tar.gz'), await download(SOURCES.scowl))
execFileSync('tar', ['-xzf', 'scowl.tar.gz'], { cwd: work })
const final = join(work, 'scowl-2020.12.07', 'final')
for (const file of readdirSync(final)) {
const list =
/^(?:english|american|british|canadian|australian)-(?:words|upper|contractions)\.(\d+)$/.exec(
file
)
if (list && Number(list[1]) <= SCOWL_MAX_SIZE) {
readFileSync(join(final, file), 'latin1').split('\n').forEach(add)
}
}
const names = async (source, limit) =>
(await download(source))
.toString('latin1')
.trim()
.split('\n')
.slice(0, limit)
.map((line) => line.split(/\s+/)[0])
for (const name of [
...(await names(SOURCES.femaleFirst)),
...(await names(SOURCES.maleFirst)),
...(await names(SOURCES.last, LAST_NAMES))
]) {
add(name)
}
const bits = Math.ceil((-words.size * Math.log(FALSE_POSITIVE_RATE)) / Math.LN2 ** 2 / 8) * 8
const hashes = Math.round((bits / words.size) * Math.LN2)
const bytes = new Uint8Array(bits / 8)
for (const word of words) {
for (const slot of wordFilterSlots(word, bits, hashes)) {
bytes[slot >>> 3] |= 1 << (slot & 7)
}
}
// The whole SCOWL notice (Atkinson, WordNet, VarCon, Ispell and the rest) rides in every bundle that keeps legal comments.
const license = readFileSync('resources/licenses/scowl/Copyright', 'utf8').trimEnd().split('\n')
const notice = [
`A filter of ${words.size} common English words and names: SCOWL 2020.12.07 words, capitalized words and`,
`contractions up to size ${SCOWL_MAX_SIZE} (english, american, british, canadian, australian), a-z only, lowercased,`,
`plus the 1990 US census first names and ${LAST_NAMES} most common last names (public domain). Generated by`,
'config/scripts/dictation/build-dictation-english-words.mjs from these SCOWL notices:',
'',
...license.map((line) => line.replaceAll('*/', '* /'))
]
writeFileSync(
OUT,
`/*! @license\n${notice.map((line) => ` * ${line}`.trimEnd()).join('\n')}\n */\n` +
`import type { WordFilter } from './dictation-word-filter'\n\n` +
`export const COMMON_ENGLISH_WORDS: WordFilter = {\n bits: ${bits},\n hashes: ${hashes},\n` +
` base64:\n '${Buffer.from(bytes).toString('base64')}'\n}\n`
)
console.log(`${OUT}: ${words.size} words, ${bits} bits, ${hashes} hashes`)
} finally {
rmSync(work, { recursive: true, force: true })
}
@@ -19,8 +19,9 @@ const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupp
const XTERM_CORE_PATCH =
/^config\/patches\/(?:@xterm__xterm@[^/]+\.patch|xterm-src\/@xterm__xterm@[^/]+\.src\.patch)$/
// Paths follow the input/ime and input/keyboard owners (#39113); the pre-move paths matched nothing.
const NATIVE_IME_PRODUCT_SOURCE =
/^(?:src\/shared\/terminal-unicode-provider\.ts$|src\/renderer\/src\/lib\/pane-manager\/terminal-ime-|src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|terminal-ios-hangul-|xterm-bypass-policy))/
/^(?:src\/shared\/terminal-unicode-provider\.ts$|src\/renderer\/src\/lib\/pane-manager\/terminal-input\/terminal-ime-|src\/renderer\/src\/components\/terminal-pane\/input\/(?:ime\/|keyboard\/xterm-bypass-policy|terminal-pane-pane-input\.ts$))/
/** The harness itself: the session runner, the boundary probes, and the native specs. */
const NATIVE_IME_HARNESS =
@@ -401,7 +402,7 @@ export const PR_E2E_SOURCE_ROUTES = [
matches: (file) =>
isProductSource(file) &&
(XTERM_CORE_PATCH.test(file) ||
/^src\/renderer\/src\/components\/terminal-pane\/(?:terminal-ime-|use-terminal-pane-lifecycle|xterm-bypass-policy|terminal-option-shortcut-policy)/.test(
/^src\/renderer\/src\/components\/terminal-pane\/(?:input\/ime\/terminal-ime-|controller\/use-terminal-pane-lifecycle|input\/keyboard\/(?:xterm-bypass-policy|terminal-option-shortcut-policy))/.test(
file
))
},
+14 -12
View File
@@ -14,18 +14,20 @@
"../src/renderer/src/**/*.tsx",
"../src/preload/api-types.ts",
"../src/preload/api/**/*",
"../src/preload/backend-port-client.ts",
"../src/preload/browser-client-page-renderer-requests.ts",
"../src/preload/browser-find-subscriptions.ts",
"../src/preload/close-active-tab-payload-admission.ts",
"../src/preload/e2e-config.ts",
"../src/preload/gitlab.ts",
"../src/preload/preload-runtime-support.ts",
"../src/preload/renderer-heap-statistics-reader.ts",
"../src/preload/renderer-process-memory-reader.ts",
"../src/preload/renderer-restart-wiring.ts",
"../src/preload/runtime-environment-subscriptions.ts",
"../src/preload/usage-provider-api.ts",
"../src/preload/index.ts",
"../src/preload/usage/backend-port-client.ts",
"../src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts",
"../src/preload/renderer/browser-pages/browser-find-subscriptions.ts",
"../src/preload/renderer/window-commands/close-active-tab-payload-admission.ts",
"../src/preload/renderer/e2e-config.ts",
"../src/preload/renderer/hidden-window-frame-pump.ts",
"../src/preload/api/gitlab.ts",
"../src/preload/renderer/renderer-runtime.ts",
"../src/preload/renderer/diagnostics/renderer-heap-statistics-reader.ts",
"../src/preload/renderer/diagnostics/renderer-process-memory-reader.ts",
"../src/preload/renderer/restart/renderer-restart-wiring.ts",
"../src/preload/runtime/runtime-environment-subscriptions.ts",
"../src/preload/usage/usage-provider-api.ts",
"../src/main/pi/rpc/options/rpc-model-schema.ts",
"../src/main/pi/rpc/options/rpc-model-options.ts",
"../src/shared/**/*",
@@ -14,7 +14,15 @@ Orca fetches usage for Claude Code, Codex, Gemini, OpenCode Go, Kimi Code, MiniM
Orca asks each provider for your usage over the network, using the login that agent already has or a key or session cookie you add in Orca Settings.
For Claude, Orca requests `https://api.anthropic.com/api/oauth/usage` with the token from your existing Claude Code login; it does not ask for extra credentials. Triggers include:
### Claude usage polling
**Settings → Accounts → Claude → Claude usage polling** is on by default. Turn it off to stop Orca's requests to `https://api.anthropic.com/api/oauth/usage`, including manual refreshes, account switching, inactive-account previews, and refreshes from mobile or web clients. Turning it off cancels pending usage requests and removes their cached figures while retaining live terminal readings. A request already sent cannot be recalled.
With polling off, the meter uses Claude Code's [status-line data](https://code.claude.com/docs/en/statusline#rate-limit-usage): five-hour and weekly percentages and reset times. This requires a supported Claude Code version and Orca's status-line feed. Orca preserves a user-owned status line, so those sessions do not supply this feed. Without a reading, usage is unavailable until a terminal session reports it. Model-specific weekly windows, credits, and inactive-account readings require polling.
The persisted setting is `claudeOAuthUsageEnabled: false` to disable polling. It applies on the host running the agents, including a headless Orca server; configure each host separately. Hiding the Claude status-bar item controls visibility independently.
When polling is enabled, Orca uses the token from your existing Claude Code login. Triggers include:
- Once the Orca window is active after startup, then about every 15 minutes while it stays visible and focused.
- Bringing the window back to the front when the last check is more than 5 minutes old (sooner after a failed check).
+248
View File
@@ -0,0 +1,248 @@
The collective work is Copyright 2000-2018 by Kevin Atkinson as well
as any of the copyrights mentioned below:
Copyright 2000-2018 by Kevin Atkinson
Permission to use, copy, modify, distribute and sell these word
lists, the associated scripts, the output created from the scripts,
and its documentation for any purpose is hereby granted without fee,
provided that the above copyright notice appears in all copies and
that both that copyright notice and this permission notice appear in
supporting documentation. Kevin Atkinson makes no representations
about the suitability of this array for any purpose. It is provided
"as is" without express or implied warranty.
Alan Beale <biljir@pobox.com> also deserves special credit as he has,
in addition to providing the 12Dicts package and being a major
contributor to the ENABLE word list, given me an incredible amount of
feedback and created a number of special lists (those found in the
Supplement) in order to help improve the overall quality of SCOWL.
The 10 level includes the 1000 most common English words (according to
the Moby (TM) Words II [MWords] package), a subset of the 1000 most
common words on the Internet (again, according to Moby Words II), and
frequently class 16 from Brian Kelk's "UK English Wordlist
with Frequency Classification".
The MWords package was explicitly placed in the public domain:
The Moby lexicon project is complete and has
been place into the public domain. Use, sell,
rework, excerpt and use in any way on any platform.
Placing this material on internal or public servers is
also encouraged. The compiler is not aware of any
export restrictions so freely distribute world-wide.
You can verify the public domain status by contacting
Grady Ward
3449 Martha Ct.
Arcata, CA 95521-4884
grady@netcom.com
grady@northcoast.com
The "UK English Wordlist With Frequency Classification" is also in the
Public Domain:
Date: Sat, 08 Jul 2000 20:27:21 +0100
From: Brian Kelk <Brian.Kelk@cl.cam.ac.uk>
> I was wondering what the copyright status of your "UK English
> Wordlist With Frequency Classification" word list as it seems to
> be lacking any copyright notice.
There were many many sources in total, but any text marked
"copyright" was avoided. Locally-written documentation was one
source. An earlier version of the list resided in a filespace called
PUBLIC on the University mainframe, because it was considered public
domain.
Date: Tue, 11 Jul 2000 19:31:34 +0100
> So are you saying your word list is also in the public domain?
That is the intention.
The 20 level includes frequency classes 7-15 from Brian's word list.
The 35 level includes frequency classes 2-6 and words appearing in at
least 11 of 12 dictionaries as indicated in the 12Dicts package. All
words from the 12Dicts package have had likely inflections added via
my inflection database.
The 12Dicts package and Supplement is in the Public Domain.
The WordNet database, which was used in the creation of the
Inflections database, is under the following copyright:
This software and database is being provided to you, the LICENSEE,
by Princeton University under the following license. By obtaining,
using and/or copying this software and database, you agree that you
have read, understood, and will comply with these terms and
conditions.:
Permission to use, copy, modify and distribute this software and
database and its documentation for any purpose and without fee or
royalty is hereby granted, provided that you agree to comply with
the following copyright notice and statements, including the
disclaimer, and that the same appear on ALL copies of the software,
database and documentation, including modifications that you make
for internal use or for distribution.
WordNet 1.6 Copyright 1997 by Princeton University. All rights
reserved.
THIS SOFTWARE AND DATABASE IS PROVIDED "AS IS" AND PRINCETON
UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PRINCETON
UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES OF MERCHANT-
ABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE
LICENSED SOFTWARE, DATABASE OR DOCUMENTATION WILL NOT INFRINGE ANY
THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
The name of Princeton University or Princeton may not be used in
advertising or publicity pertaining to distribution of the software
and/or database. Title to copyright in this software, database and
any associated documentation shall at all times remain with
Princeton University and LICENSEE agrees to preserve same.
The 40 level includes words from Alan's 3esl list found in version 4.0
of his 12dicts package. Like his other stuff the 3esl list is also in the
public domain.
The 50 level includes Brian's frequency class 1, words appearing
in at least 5 of 12 of the dictionaries as indicated in the 12Dicts
package, and uppercase words in at least 4 of the previous 12
dictionaries. A decent number of proper names is also included: The
top 1000 male, female, and Last names from the 1990 Census report; a
list of names sent to me by Alan Beale; and a few names that I added
myself. Finally a small list of abbreviations not commonly found in
other word lists is included.
The name files form the Census report is a government document which I
don't think can be copyrighted.
The file special-jargon.50 uses common.lst and word.lst from the
"Unofficial Jargon File Word Lists" which is derived from "The Jargon
File". All of which is in the Public Domain. This file also contain
a few extra UNIX terms which are found in the file "unix-terms" in the
special/ directory.
The 55 level includes words from Alan's 2of4brif list found in version
4.0 of his 12dicts package. Like his other stuff the 2of4brif is also
in the public domain.
The 60 level includes all words appearing in at least 2 of the 12
dictionaries as indicated by the 12Dicts package.
The 70 level includes Brian's frequency class 0 and the 74,550 common
dictionary words from the MWords package. The common dictionary words,
like those from the 12Dicts package, have had all likely inflections
added. The 70 level also included the 5desk list from version 4.0 of
the 12Dics package which is in the public domain.
The 80 level includes the ENABLE word list, all the lists in the
ENABLE supplement package (except for ABLE), the "UK Advanced Cryptics
Dictionary" (UKACD), the list of signature words from the YAWL package,
and the 10,196 places list from the MWords package.
The ENABLE package, mainted by M\Cooper <thegrendel@theriver.com>,
is in the Public Domain:
The ENABLE master word list, WORD.LST, is herewith formally released
into the Public Domain. Anyone is free to use it or distribute it in
any manner they see fit. No fee or registration is required for its
use nor are "contributions" solicited (if you feel you absolutely
must contribute something for your own peace of mind, the authors of
the ENABLE list ask that you make a donation on their behalf to your
favorite charity). This word list is our gift to the Scrabble
community, as an alternate to "official" word lists. Game designers
may feel free to incorporate the WORD.LST into their games. Please
mention the source and credit us as originators of the list. Note
that if you, as a game designer, use the WORD.LST in your product,
you may still copyright and protect your product, but you may *not*
legally copyright or in any way restrict redistribution of the
WORD.LST portion of your product. This *may* under law restrict your
rights to restrict your users' rights, but that is only fair.
UKACD, by J Ross Beresford <ross@bryson.demon.co.uk>, is under the
following copyright:
Copyright (c) J Ross Beresford 1993-1999. All Rights Reserved.
The following restriction is placed on the use of this publication:
if The UK Advanced Cryptics Dictionary is used in a software package
or redistributed in any form, the copyright notice must be
prominently displayed and the text of this document must be included
verbatim.
There are no other restrictions: I would like to see the list
distributed as widely as possible.
The 95 level includes the 354,984 single words, 256,772 compound
words, 4,946 female names and the 3,897 male names, and 21,986 names
from the MWords package, ABLE.LST from the ENABLE Supplement, and some
additional words found in my part-of-speech database that were not
found anywhere else.
Accent information was taken from UKACD.
The VarCon package was used to create the American, British, Canadian,
and Australian word list. It is under the following copyright:
Copyright 2000-2016 by Kevin Atkinson
Permission to use, copy, modify, distribute and sell this array, the
associated software, and its documentation for any purpose is hereby
granted without fee, provided that the above copyright notice appears
in all copies and that both that copyright notice and this permission
notice appear in supporting documentation. Kevin Atkinson makes no
representations about the suitability of this array for any
purpose. It is provided "as is" without express or implied warranty.
Copyright 2016 by Benjamin Titze
Permission to use, copy, modify, distribute and sell this array, the
associated software, and its documentation for any purpose is hereby
granted without fee, provided that the above copyright notice appears
in all copies and that both that copyright notice and this permission
notice appear in supporting documentation. Benjamin Titze makes no
representations about the suitability of this array for any
purpose. It is provided "as is" without express or implied warranty.
Since the original words lists come from the Ispell distribution:
Copyright 1993, Geoff Kuenning, Granada Hills, CA
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. All modifications to the source code must be clearly marked as
such. Binary redistributions based on modified source code
must be clearly marked as modified versions in the documentation
and/or other materials provided with the distribution.
(clause 4 removed with permission from Geoff Kuenning)
5. The name of Geoff Kuenning may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
+2
View File
@@ -185,6 +185,8 @@ export type AcpDialect = {
text(value: string): string
reply(text: string): AcpModelCommandReply
}
/** The agent reads a mentioned file only from a resource link, not from `@path` text. */
linksFileMentions?: true
/** Hide these commands and reject command-only prompts before dispatch. */
withheldCommands?: readonly string[]
/** Which sign-in a not-signed-in chat needs; absent is the agent's usual one. */
@@ -111,6 +111,7 @@ export const OPENCODE_ACP_DIALECT: AcpDialect = {
supported: (initialized) => initialized.agentCapabilities?.sessionCapabilities?.close != null
},
effortChangesModel: true,
linksFileMentions: true,
normalizeToolUpdate,
notification: openCodeChildUpdate,
promptFailure
@@ -256,6 +256,7 @@ export async function acquireAcpStructuredSession(input: {
fence: acquire.fence,
acquisitionGeneration: generation,
spec,
cwd: launch.cwd,
permissionModes,
connection,
lane: null,
@@ -15,6 +15,8 @@ export type AcpStructuredSession = {
fence: number
acquisitionGeneration: string
spec: AcpLaunchSpec
/** The session's folder on the agent's host. */
cwd: string
/** Session modes this launch reports as Orca's permission modes. */
permissionModes: Readonly<Partial<Record<AgentChatPermissionMode, string>>> | undefined
childStops?: AcpChildStops
@@ -12,6 +12,7 @@ export type AcpStructuredChild = Pick<
| 'fence'
| 'acquisitionGeneration'
| 'spec'
| 'cwd'
| 'permissionModes'
| 'connection'
| 'closeRequested'
@@ -0,0 +1,66 @@
import { realpath, stat } from 'node:fs/promises'
import { isAbsolute, relative, resolve, sep } from 'node:path'
import { pathToFileURL } from 'node:url'
import { nativeChatTextAttachmentParts } from '../../../shared/native-chat-text-attachment-references'
import type { ContentBlock } from '../generated/acp-protocol.generated'
const TRAILING_PUNCTUATION = /[.,;:!?)\]}`"'*]+$/
/** The real path of a file inside `realRoot`; symlinks and `..` cannot leave it. */
async function fileInside(
realRoot: string,
path: string,
maxBytes: number
): Promise<string | null> {
const target = await realpath(resolve(realRoot, path)).catch(() => null)
// Byte-exact: Unicode or case folding would admit a sibling folder on Linux.
const inside = target ? relative(realRoot, target) : ''
if (
!target ||
!inside ||
inside === '..' ||
inside.startsWith(`..${sep}`) ||
isAbsolute(inside)
) {
return null
}
return (await stat(target).then(
(info) => info.isFile() && info.size <= maxBytes,
() => false
))
? target
: null
}
/** One link per `@path` naming a file inside `root`; larger files stay text for the agent's own tools. */
export async function acpFileMentionLinks(
texts: readonly string[],
root: string,
maxBytes: number
): Promise<ContentBlock[]> {
const paths = new Set(
texts.flatMap((text) =>
nativeChatTextAttachmentParts(text, true, () => true).flatMap((part) =>
part.path ? [part.path] : []
)
)
)
const realRoot = paths.size > 0 ? await realpath(root).catch(() => null) : null
if (!realRoot) {
return []
}
const links = new Map<string, ContentBlock>()
for (const path of paths) {
// Punctuation after a mention belongs to the sentence unless the name itself exists.
const trimmed = path.replace(TRAILING_PUNCTUATION, '')
const literal = await fileInside(realRoot, path, maxBytes)
const name = literal ? path : trimmed
const target =
literal ??
(trimmed && trimmed !== path ? await fileInside(realRoot, trimmed, maxBytes) : null)
if (target && !links.has(target)) {
links.set(target, { type: 'resource_link', uri: pathToFileURL(target).href, name })
}
}
return [...links.values()]
}
+33 -1
View File
@@ -1,6 +1,7 @@
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { afterAll, describe, expect, it } from 'vitest'
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
@@ -64,4 +65,35 @@ describe('ACP prompt content', () => {
attachment: { reason: 'totalTooLarge' }
})
})
it('links mentioned files inside the session folder and keeps the text as typed', async () => {
const root = join(dir, 'project')
mkdirSync(join(root, 'my dir'), { recursive: true })
writeFileSync(join(root, 'a.txt'), 'a')
writeFileSync(join(root, 'my dir', 'b.txt'), 'b')
writeFileSync(join(root, "it's.txt"), 'c')
writeFileSync(join(root, 'report!'), 'd')
writeFileSync(join(root, 'report'), 'e')
// OpenCode 2 fails the whole turn for a linked file over 20 MiB.
writeFileSync(join(root, 'big.log'), Buffer.alloc(20 * 1024 * 1024 + 1))
mkdirSync(join(dir, 'outside'))
writeFileSync(join(dir, 'outside', 'c.txt'), 'secret')
// A junction needs no privilege on Windows.
symlinkSync(join(dir, 'outside'), join(root, 'escape'), 'junction')
const text =
'Read @a.txt. and @"my dir/b.txt" @it\'s.txt, see:@report! not @../outside/c.txt @escape/c.txt @missing.txt @big.log'
const real = realpathSync(root)
expect(await acpPromptBlocks(message({ type: 'text', text }), true, root)).toEqual([
{ type: 'text', text },
{ type: 'resource_link', uri: pathToFileURL(join(real, 'a.txt')).href, name: 'a.txt' },
{
type: 'resource_link',
uri: pathToFileURL(join(real, 'my dir', 'b.txt')).href,
name: 'my dir/b.txt'
},
{ type: 'resource_link', uri: pathToFileURL(join(real, "it's.txt")).href, name: "it's.txt" },
{ type: 'resource_link', uri: pathToFileURL(join(real, 'report!')).href, name: 'report!' }
])
})
})
+21 -7
View File
@@ -26,13 +26,14 @@ import { acpAgentName } from '../session/acp-structured-agent-definitions'
import type { AcpStructuredConnection } from '../process/acp-structured-connection'
import { acpSessionAcceptsImages } from '../protocol/acp-image-capability'
import type { ContentBlock } from '../generated/acp-protocol.generated'
import { acpFileMentionLinks } from './acp-file-mention-links'
// Reserve space for the JSON-RPC envelope around the prompt blocks.
const ACP_PROMPT_LINE_BUDGET = ACP_MAX_LINE_BYTES - 64 * 1024
// Budget raw images for base64's 4:3 expansion and leave room for text.
const ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES = Math.floor((ACP_PROMPT_LINE_BUDGET * 3) / 4) - 1024 * 1024
// OpenCode 2 fails the turn for any attachment over 20 MiB.
const ACP_PROMPT_PER_IMAGE_MAX_BYTES = 20 * 1024 * 1024
// OpenCode 2 fails the turn for any image or linked file over 20 MiB.
const ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES = 20 * 1024 * 1024
const MAX_IMAGE_COUNT = 20
const READ_TIMEOUT_MS = 15_000
@@ -74,8 +75,8 @@ async function imageBlock(
if (bytes === 0) {
throw attachmentProblem({ reason: 'empty' })
}
if (bytes > ACP_PROMPT_PER_IMAGE_MAX_BYTES) {
throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_IMAGE_MAX_BYTES })
if (bytes > ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES) {
throw attachmentProblem({ reason: 'tooLarge', limit: ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES })
}
if (bytes > remainingBytes) {
throw attachmentProblem({ reason: 'totalTooLarge', limit: ACP_PROMPT_TOTAL_IMAGE_MAX_BYTES })
@@ -91,7 +92,7 @@ async function imageBlock(
block: { type: 'text' as const, text: formatNativeChatFileReference(path) },
bytes: 0
}
const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_IMAGE_MAX_BYTES)
const maxBytes = Math.min(remainingBytes, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES)
if (!mimeType || maxBytes <= 0) {
return fallback
}
@@ -119,9 +120,11 @@ async function imageBlock(
return { block: { type: 'image', mimeType, data: data.toString('base64') }, bytes: data.length }
}
/** `mentionRoot` links each `@path` there, for agents that read only linked files. */
export async function acpPromptBlocks(
body: AgentJournalMessageItem,
acceptsImages: boolean
acceptsImages: boolean,
mentionRoot?: string
): Promise<ContentBlock[]> {
// Reserve later text and file references before allocating image capacity.
const blocks: ContentBlock[] = body.blocks.map((block) => {
@@ -131,6 +134,12 @@ export async function acpPromptBlocks(
const path = block.type === 'image-ref' ? hostImagePath(block) : null
return { type: 'text', text: path ? formatNativeChatFileReference(path) : '' }
})
if (mentionRoot !== undefined) {
const texts = body.blocks.flatMap((block) => (block.type === 'text' ? [block.text] : []))
blocks.push(
...(await acpFileMentionLinks(texts, mentionRoot, ACP_PROMPT_PER_ATTACHMENT_MAX_BYTES))
)
}
const blockBytes = (block: ContentBlock): number => Buffer.byteLength(JSON.stringify(block))
let encodedBytes =
2 + Math.max(0, blocks.length - 1) + blocks.reduce((n, b) => n + blockBytes(b), 0)
@@ -194,6 +203,7 @@ export async function acpDispatchPrompt(
session: {
spec: Pick<AcpLaunchSpec, 'agent' | 'dialect'>
connection: Pick<AcpStructuredConnection, 'initialize'>
cwd: string
}
): Promise<ContentBlock[] | AgentJournalDispatchRejection> {
if (isWithheldCommand(body, session.spec.dialect.withheldCommands ?? [])) {
@@ -203,7 +213,11 @@ export async function acpDispatchPrompt(
})
}
try {
return await acpPromptBlocks(body, await acpSessionAcceptsImages(session))
return await acpPromptBlocks(
body,
await acpSessionAcceptsImages(session),
session.spec.dialect.linksFileMentions ? session.cwd : undefined
)
} catch (error) {
if (error instanceof AcpPromptContentError) {
return agentSessionFailureWords(error.failure, {
@@ -228,7 +228,12 @@ async function runFixture(): Promise<FixtureResult> {
const resultPath = join(root, 'result.json')
writeFileSync(
preloadSource,
preloadEntry(join(process.cwd(), 'src/preload/browser-client-page-renderer-requests.ts'))
preloadEntry(
join(
process.cwd(),
'src/preload/renderer/browser-pages/browser-client-page-renderer-requests.ts'
)
)
)
writeFileSync(
rendererSource,
@@ -70,7 +70,7 @@ mocks.userData = mkdtempSync(join(tmpdir(), 'orca-extension-api-host-'))
const { BROWSER_EXTENSION_INVOKE_CHANNEL } =
await import('../../../../shared/browser/extensions/browser-extension-channels')
await import('../../../../preload/browser-extension-api-surface')
await import('../../../../preload/browser/extensions/api/browser-extension-api-surface')
const registry = await import('./browser-extension-namespace-registry')
const host = await import('./browser-extension-api-host')
const contexts = await import('./browser-extension-contexts')
@@ -180,22 +180,6 @@ describe('extension API host', () => {
})
})
it('retires the current host after extension support restarts in the same document', async () => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the session boundary copies the extensions, serviceWorkers and protocol members consumed by the actual host.
const isolated = { ...extensionSession } as unknown as Electron.Session
host.attachBrowserExtensionApiHostToSession(isolated, 'restarted')
const current = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, isolated, 10, 1)
const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true }
await invoke(current.event, listen)
host.forgetBrowserExtensionContexts(isolated)
host.attachBrowserExtensionApiHostToSession(isolated, 'restarted')
await invoke(current.event, listen)
current.event.sender.emit('did-navigate')
expect(contexts.getHostSessionState(isolated)?.frames.size).toBe(0)
expect(contexts.browserExtensionEventHasListener(isolated, 'probe', 'onPing')).toBe(false)
host.forgetBrowserExtensionContexts(isolated)
})
describe('extension subframe listener retirement', () => {
const listen = { type: 'listen', namespace: 'probe', event: 'onPing', active: true }
@@ -218,66 +202,6 @@ describe('extension subframe listener retirement', () => {
return current
}
it('shares one port across listeners and replaces it after final removal', async () => {
const { sess, state } = isolatedSession()
const page = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 21, 1)
await invoke(page.event, listen)
const first = channel()
const lateClose = first.port1.listeners('close')[0]
await invoke(page.event, listen)
await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated' })
expect(page.frame.postMessage).toHaveBeenCalledTimes(1)
await invoke(page.event, { ...listen, active: false })
expect(state.frames.size).toBe(1)
expect(first.port1.close).not.toHaveBeenCalled()
await invoke(page.event, { ...listen, namespace: 'tabs', event: 'onCreated', active: false })
expect(state.frames.size).toBe(0)
expect(first.port1.close).toHaveBeenCalledTimes(1)
expect(first.port1.listenerCount('close')).toBe(0)
await invoke(page.event, listen)
expect(channel()).not.toBe(first)
lateClose?.()
host.emitBrowserExtensionEvent({ session: sess }, 'probe', 'onPing', ['successor'])
expect(page.frame.send).toHaveBeenCalledTimes(1)
expect(state.frames.size).toBe(1)
host.forgetBrowserExtensionContexts(sess)
})
it('preserves sibling frames, windows, sessions and worker listeners', async () => {
const { sess, state } = isolatedSession()
const elsewhere = isolatedSession()
const removed = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 1)
const sibling = frameEvent(`chrome-extension://${EXTENSION_ID}/frame.html`, sess, 22, 2)
sibling.event.sender = removed.event.sender
const window = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, sess, 22, 3)
window.event.sender.id = 78
const other = frameEvent(`chrome-extension://${EXTENSION_ID}/page.html`, elsewhere.sess, 23, 1)
await invoke(removed.event, listen)
const owner = channel()
await invoke(sibling.event, listen)
await invoke(window.event, listen)
await invoke(other.event, listen)
const worker = contexts.ensureWorkerContext(
state,
EXTENSION_ID,
`chrome-extension://${EXTENSION_ID}/`
)
worker.events.add('probe.onPing')
worker.stream = { send: vi.fn(), close: vi.fn() }
owner.port1.emit('close')
host.emitBrowserExtensionEvent({}, 'probe', 'onPing', ['survivors'])
expect(removed.frame.send).not.toHaveBeenCalled()
for (const frame of [sibling.frame, window.frame, other.frame]) {
expect(frame.send).toHaveBeenCalledTimes(1)
}
expect(worker.stream.send).toHaveBeenCalledTimes(1)
expect(worker.stream.close).not.toHaveBeenCalled()
expect(state.frames.size).toBe(2)
expect(elsewhere.state.frames.size).toBe(1)
host.forgetBrowserExtensionContexts(sess)
host.forgetBrowserExtensionContexts(elsewhere.sess)
})
it('keeps extension membership snapshotted while resolving current frames after callbacks', async () => {
const { sess } = isolatedSession()
const first = frameEvent(`chrome-extension://${EXTENSION_ID}/first.html`, sess, 41, 1)
@@ -1,194 +0,0 @@
import { mkdtempSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runInNewContext } from 'node:vm'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ContentScriptMethod } from './browser-extension-content-scripts'
type Script = Record<string, unknown> & { id: string }
const mocks = vi.hoisted(() => ({
directory: '',
scripts: new Map<string, Script>(),
beforeExecute: async (): Promise<void> => {},
beforeCallback: async (): Promise<void> => {},
nativeError: '',
windows: new Array<{ options: unknown; destroyed: boolean }>()
}))
vi.mock('electron', () => ({
app: { on() {} },
webFrameMain: { fromId() {} },
BrowserWindow: class {
record: { options: unknown; destroyed: boolean }
constructor(options: unknown) {
this.record = { options, destroyed: false }
mocks.windows.push(this.record)
}
async loadURL() {}
webContents = {
executeJavaScript: async (code: string) => {
await mocks.beforeExecute()
const runtime: { lastError?: { message: string } } = {}
const complete = async (callback: (value?: unknown) => void, value?: unknown) => {
await mocks.beforeCallback()
if (mocks.nativeError) {
runtime.lastError = { message: mocks.nativeError }
}
callback(value)
delete runtime.lastError
}
return runInNewContext(code, {
chrome: {
runtime,
scripting: {
registerContentScripts(scripts: Script[], callback: () => void) {
if (!mocks.nativeError) {
for (const script of scripts) {
if (mocks.scripts.has(script.id)) {
runtime.lastError = { message: 'Duplicate script ID' }
callback()
delete runtime.lastError
return
}
mocks.scripts.set(script.id, { ...script })
}
}
complete(callback)
},
updateContentScripts(updates: Script[], callback: () => void) {
if (!mocks.nativeError) {
for (const update of updates) {
mocks.scripts.set(update.id, { ...mocks.scripts.get(update.id), ...update })
}
}
complete(callback)
},
unregisterContentScripts(filter: { ids?: string[] }, callback: () => void) {
for (const id of filter.ids ?? [...mocks.scripts.keys()]) {
mocks.scripts.delete(id)
}
complete(callback)
},
getRegisteredContentScripts(
filterOrCallback: { ids?: string[] } | ((value: Script[]) => void),
callback?: (value: Script[]) => void
) {
const filter = typeof filterOrCallback === 'function' ? {} : filterOrCallback
const done = typeof filterOrCallback === 'function' ? filterOrCallback : callback
done?.(
[...mocks.scripts.values()]
.filter((script) => !filter.ids || filter.ids.includes(script.id))
.map((script) => ({ ...script }))
)
}
}
}
})
}
}
destroy() {
this.record.destroyed = true
}
}
}))
vi.mock('../profile-storage/browser-extension-profile-data-directory', () => ({
getBrowserExtensionProfileDataDirectory: () => mocks.directory
}))
mocks.directory = mkdtempSync(join(tmpdir(), 'orca-content-script-persistence-'))
const registry = await import('./browser-extension-namespace-registry')
const { registerScriptingNamespaces } = await import('../api/scripting')
const { forgetBrowserExtensionContentScriptRestore, restoreBrowserExtensionContentScripts } =
await import('./browser-extension-content-scripts')
const { getBrowserExtensionProfileStateStore } =
await import('../profile-storage/browser-extension-profile-state-store')
const { installBrowserExtensionApis } =
await import('../../../../preload/browser-extension-main-world')
const { BROWSER_EXTENSION_API_SURFACE } =
await import('../../../../preload/browser-extension-api-surface')
const extension: Electron.Extension = {
id: 'a'.repeat(32),
name: 'Popup only',
version: '1',
path: '/example',
url: '',
manifest: {
manifest_version: 3,
permissions: ['scripting'],
action: { default_popup: 'popup.html' }
}
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: native page creation is mocked; the owner only uses session identity.
const session = {} as Electron.Session
const store = getBrowserExtensionProfileStateStore()
const stored = () => store.read('default', extension.id).contentScripts
function context(fromWorker: boolean) {
const scripting: Partial<Record<ContentScriptMethod, unknown>> = {}
const chrome = { runtime: { getManifest: () => extension.manifest }, scripting }
const bridge = {
call: async (namespace: string, method: string, args: unknown[]) => ({
ok: true,
value: await registry
.getBrowserExtensionNamespace(namespace)
?.methods[method].invoke(
{ extension, session, browserProfileId: 'default', fromWorker },
args
)
}),
listen() {},
onEvent() {},
passesFilter: () => true
}
runInNewContext(`(${installBrowserExtensionApis.toString()})(bridge, surface)`, {
chrome,
bridge,
console,
surface: { scripting: BROWSER_EXTENSION_API_SURFACE.scripting }
})
const call = async (method: ContentScriptMethod, ...args: unknown[]) => {
const fn = chrome.scripting[method]
if (typeof fn !== 'function') {
throw new Error('Missing scripting method')
}
return fn(...args)
}
return call
}
registerScriptingNamespaces()
beforeEach(() => {
forgetBrowserExtensionContentScriptRestore(session, extension.id)
mocks.scripts.clear()
mocks.windows.length = 0
mocks.beforeExecute = async () => {}
mocks.beforeCallback = async () => {}
mocks.nativeError = ''
store.update('default', extension.id, (state) => ({ ...state, contentScripts: [] }))
})
describe('native content script ownership', () => {
it('retires timed-out native work instead of allowing a successor to overlap it', async () => {
const script = { id: 'saved', js: ['saved.js'] }
store.update('default', extension.id, (state) => ({ ...state, contentScripts: [script] }))
let release = () => {}
let completed = () => {}
const nativeCompleted = new Promise<void>((resolve) => {
completed = resolve
})
mocks.beforeCallback = () =>
new Promise<void>((resolve) => {
release = () => {
resolve()
completed()
}
})
await expect(
restoreBrowserExtensionContentScripts(session, 'default', extension, 1)
).rejects.toThrow('timed out')
await expect(context(false)('unregisterContentScripts', {})).rejects.toThrow('timed out')
expect(mocks.windows).toHaveLength(1)
expect(mocks.windows[0].destroyed).toBe(true)
expect([...mocks.scripts.values()]).toEqual([script])
release()
await nativeCompleted
expect(stored()).toEqual([script])
})
})
@@ -72,15 +72,10 @@ const { getBrowserExtensionProfileStateStore } =
const menuHost = await import('../context-menus/browser-extension-context-menu-host')
const webRequest = await import('../requests/browser-extension-web-request-observer')
const { setBrowserExtensionSupportEnabled } = await import('../browser-extension-support')
const contexts = await import('../api-runtime/browser-extension-contexts')
const eventDispatch = await import('../api-runtime/browser-extension-event-dispatch')
const { attachWorkerEventStream } =
await import('../api-runtime/browser-extension-worker-event-stream')
const { handleBrowserExtensionApiRequest } =
await import('../api-runtime/browser-extension-api-request')
await import('../../../../preload/browser-extension-storage-relay')
await import('../../../../preload/browser/extensions/storage/browser-extension-storage-relay')
const { PRELOAD_STORAGE_SYNC_NAMESPACE } =
await import('../../../../preload/browser-extension-storage-sync')
await import('../../../../preload/browser/extensions/storage/browser-extension-storage-sync')
const VAULT = 'a'.repeat(32)
const OTHER = 'b'.repeat(32)
@@ -205,79 +200,6 @@ beforeEach(() => {
mocks.prompt.mockReset()
})
describe('permissions.request', () => {
it.each(['extension unload', 'profile deletion'] as const)(
'does not recreate grants when accepted after %s',
async (reason) => {
const extensionId = (reason === 'extension unload' ? 'd' : 'e').repeat(32)
extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] }))
let answer: (accepted: boolean) => void = () => {}
mocks.prompt.mockReturnValueOnce(
new Promise((resolve) => {
answer = resolve
})
)
const pending = call(
extensionId,
'permissions',
'request',
[{ permissions: ['privacy'] }],
'page'
)
const store = getBrowserExtensionProfileStateStore()
if (reason === 'extension unload') {
extensionSession.extensions.emit('extension-unloaded', {}, extensions.get(extensionId))
store.forgetExtension(extensionId)
} else {
host.forgetBrowserExtensionContexts(session)
store.forgetProfile('default')
}
answer(true)
await expect(pending).resolves.toBe(false)
expect(store.readProfile('default')).not.toHaveProperty(extensionId)
host.attachBrowserExtensionApiHostToSession(session, 'default')
}
)
it('delivers a previously registered optional event only while permission is granted', async () => {
const extensionId = 'f'.repeat(32)
extensions.set(extensionId, makeExtension(extensionId, { optional_permissions: ['privacy'] }))
const event = 'services.passwordSavingEnabled.onChange'
const frame = await listenFrame(extensionId, 'privacy', event)
const state = contexts.getHostSessionState(session)
if (!state) {
throw new Error('Session not attached')
}
const worker = contexts.ensureWorkerContext(
state,
extensionId,
`chrome-extension://${extensionId}/`
)
const listen = () =>
handleBrowserExtensionApiRequest(
caller(extensionId),
state,
{ type: 'listen', namespace: 'privacy', event, active: true },
{ kind: 'worker', context: worker }
)
await expect(listen()).resolves.toEqual({ ok: true, value: undefined })
host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }])
expect(frame.payloads()).toEqual([])
mocks.prompt.mockResolvedValueOnce(true)
await call(extensionId, 'permissions', 'request', [{ permissions: ['privacy'] }], 'page')
host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: false }])
expect(frame.payloads()).toEqual([[{ value: false }]])
expect(worker.queue).toHaveLength(1)
await call(extensionId, 'permissions', 'remove', [{ permissions: ['privacy'] }])
const send = vi.fn()
attachWorkerEventStream(worker, { send, close() {} })
await expect(listen()).resolves.toEqual({ ok: true, value: undefined })
expect(send).not.toHaveBeenCalled()
host.emitBrowserExtensionEvent({ session, extensionId }, 'privacy', event, [{ value: true }])
expect(frame.payloads()).toEqual([[{ value: false }]])
})
})
describe('context menus in the page menu', () => {
const guest = {
id: 900,
@@ -379,63 +301,10 @@ describe('storage.sync', () => {
)
}
function listeningWorker(sess: Electron.Session, extensionId: string) {
const state = contexts.getHostSessionState(sess)
if (!state) {
throw new Error('Session is not attached')
}
const context = contexts.ensureWorkerContext(
state,
extensionId,
`chrome-extension://${extensionId}/`
)
context.events.add(eventDispatch.eventKey(SYNC, 'onChanged'))
const send = vi.fn()
attachWorkerEventStream(context, { send, close: vi.fn() })
return { changes: () => send.mock.calls.map(([payload]) => payload.args) }
}
beforeEach(async () => {
await sync('clear', [])
})
it('sends exact old and new values to the extension pages and worker in that session only', async () => {
host.attachBrowserExtensionApiHostToSession(workSession, 'work')
const worker = listeningWorker(session, VAULT)
const page = await listenFrame(VAULT, SYNC, 'onChanged')
const otherExtension = listeningWorker(session, OTHER)
const otherProfile = listeningWorker(workSession, VAULT)
const fromPage = { kind: 'page' } as const
const written = { a: { newValue: 1 }, b: { newValue: { deep: [1] } } }
// The writer gets its changes back and fires its own listeners.
await expect(sync('set', [{ a: 1, b: { deep: [1] } }], fromPage)).resolves.toEqual(written)
await sync('set', [{ a: 1, b: { deep: [2] } }], fromPage)
await expect(sync('set', [{ a: 1 }], fromPage)).resolves.toEqual({})
await sync('remove', [['a', 'missing']], fromPage)
await sync('clear', [], fromPage)
await sync('clear', [], fromPage)
const expected = [
[written],
[{ b: { oldValue: { deep: [1] }, newValue: { deep: [2] } } }],
[{ a: { oldValue: 1 } }],
[{ b: { oldValue: { deep: [2] } } }]
]
expect(worker.changes()).toEqual(expected)
expect(page.payloads()).toEqual(expected)
expect(otherExtension.changes()).toEqual([])
expect(otherProfile.changes()).toEqual([])
await sync('set', [{ fromWorker: 1 }])
expect(worker.changes()).toHaveLength(4)
expect(page.payloads().at(-1)).toEqual([{ fromWorker: { newValue: 1 } }])
await sync('set', [{ mine: true }])
await expect(sync('get', [null], { extensionId: OTHER })).resolves.toEqual({})
await expect(sync('get', [null], { profile: 'work' })).resolves.toEqual({})
await sync('clear', [])
})
it('validates an atomic batch against its final size regardless of key order', async () => {
const initial = Object.fromEntries(
Array.from({ length: 12 }, (_, index) => [`key${index}`, 'x'.repeat(8000)])
@@ -29,14 +29,12 @@ const { attachBrowserExtensionDnr, getDnrSessionRuntime } =
const { browserExtensionDnrRequestDecider: decider } =
await import('../declarative-net-request/session/browser-extension-dnr-requests')
await import('../declarative-net-request/session/browser-extension-dnr-limits')
await import('../../../../preload/browser-extension-api-surface')
await import('../../../../preload/browser/extensions/api/browser-extension-api-surface')
const { getBrowserExtensionDnrStore } =
await import('../declarative-net-request/session/browser-extension-dnr-store')
const { registerPermissionsNamespace } = await import('./permissions')
const { ensureHostSessionState } = await import('../api-runtime/browser-extension-contexts')
const { getBrowserExtensionInstallStore } =
await import('../installation/browser-extension-install-store')
registerPermissionsNamespace()
registerDeclarativeNetRequestNamespace()
@@ -132,137 +130,4 @@ describe('chrome.declarativeNetRequest', () => {
expect(next.blocks('https://z.example/1.js')).toBe(true)
await next.call('updateDynamicRules', { removeRuleIds: [1, 3] })
})
it('switches static rulesets, and an update brings back the manifest choice', async () => {
const { call, blocks } = await launch()
await expect(call('getEnabledRulesets')).resolves.toEqual(['a'])
await call('updateEnabledRulesets', { enableRulesetIds: ['b'], disableRulesetIds: ['a'] })
expect(blocks('https://b.example/x.js')).toBe(true)
expect(blocks('https://a.example/x.js')).toBe(false)
await expect(call('updateEnabledRulesets', { enableRulesetIds: ['zzz'] })).rejects.toThrow(
'Invalid ruleset id: zzz.'
)
await expect(call('getAvailableStaticRuleCount')).resolves.toBe(330_000 - 2)
await expect((await launch()).call('getEnabledRulesets')).resolves.toEqual(['b'])
await expect((await launch(extension('2'))).call('getEnabledRulesets')).resolves.toEqual(['a'])
})
it('drops updates still queued when the extension unloads', async () => {
const { session } = await launch(extension('6'))
const runtime = getDnrSessionRuntime(session)
const rules = runtime?.extensions.get(ID)?.rules
const enabling = rules?.updateEnabledRulesets(['b'], [])
const disabling = rules?.updateStaticRules('a', [1], [])
runtime?.removeExtension(ID)
await enabling?.catch(() => undefined)
await expect(disabling).rejects.toThrow('Internal error.')
const next = await launch(extension('6'))
expect(next.blocks('https://a.example/x.js')).toBe(true)
})
})
describe('live DNR permission changes and precedence', () => {
it('activates optional authority immediately and preserves session rules across feedback changes', async () => {
const ext = extension()
ext.manifest.permissions = []
ext.manifest.optional_permissions = [
'declarativeNetRequestWithHostAccess',
'declarativeNetRequestFeedback'
]
const { session, call, blocks } = await launch(ext)
ensureHostSessionState(session, PROFILE)
const caller = { extension: ext, session, browserProfileId: PROFILE, userGesture: true }
const permission = (method: string, permissions: string[]) =>
registry
.getBrowserExtensionNamespace('permissions')
?.methods[method].invoke(caller, [{ permissions }])
expect(blocks('https://a.example/file')).toBe(false)
await expect(permission('request', ['declarativeNetRequestWithHostAccess'])).resolves.toBe(true)
expect(blocks('https://a.example/file')).toBe(true)
await call('updateSessionRules', { addRules: [block(21, '||session.example^')] })
await permission('request', ['declarativeNetRequestFeedback'])
expect(blocks('https://session.example/file')).toBe(true)
expect(await call('getSessionRules')).toEqual([block(21, '||session.example^')])
const runtime = getDnrSessionRuntime(session)
expect(runtime?.matched.matchedRules(ID, {})).not.toEqual([])
await permission('remove', ['declarativeNetRequestFeedback'])
expect(runtime?.matched.matchedRules(ID, {})).toEqual([])
expect(blocks('https://session.example/file')).toBe(true)
await permission('remove', ['declarativeNetRequestWithHostAccess'])
expect(blocks('https://a.example/file')).toBe(false)
expect(blocks('https://session.example/file')).toBe(false)
})
it('keeps install precedence when an older extension reloads or another profile loads in reverse order', async () => {
const store = getBrowserExtensionInstallStore()
const make = (id: string, target: string): Electron.Extension => {
const path = mkdtempSync(join(tmpdir(), 'orca-dnr-precedence-'))
writeFileSync(
join(path, 'rules.json'),
JSON.stringify([
{
id: 1,
condition: { urlFilter: '|https://tie.example/' },
action: { type: 'redirect', redirect: { url: target } }
}
])
)
store.save({
id,
name: id,
version: '1',
path,
source: 'unpacked',
iconPath: null,
permissions: ['declarativeNetRequest'],
hostPermissions: ['<all_urls>'],
optionsPage: null
})
return {
id,
name: id,
version: '1',
path,
url: '',
manifest: {
permissions: ['declarativeNetRequest'],
host_permissions: ['<all_urls>'],
declarative_net_request: {
rule_resources: [{ id: 'rules', enabled: true, path: 'rules.json' }]
}
}
}
}
const older = make('a'.repeat(32), 'https://older.example/')
const newer = make('b'.repeat(32), 'https://newer.example/')
const first = await launch(older)
const runtime = getDnrSessionRuntime(first.session)
if (!runtime) {
throw new Error('Missing DNR runtime')
}
await runtime.addExtension(newer)
const winner = (owner: typeof runtime) =>
owner.engine.evaluateBeforeRequest(
{
url: 'https://tie.example/file',
method: 'GET',
type: 'script',
initiator: null,
tabId: TAB
},
{ allowByExtension: new Map(), actions: [] },
{ hostAccess: () => 'allowed' }
).actions[0]?.redirectUrl
expect(winner(runtime)).toBe('https://newer.example/')
runtime.removeExtension(older.id)
await runtime.addExtension(older)
expect(winner(runtime)).toBe('https://newer.example/')
const second = await launch(newer)
const reversed = getDnrSessionRuntime(second.session)
if (!reversed) {
throw new Error('Missing DNR runtime')
}
await reversed.addExtension(older)
expect(winner(reversed)).toBe('https://newer.example/')
})
})
@@ -9,7 +9,7 @@ import {
/**
* Electron never fires chrome.storage.onChanged in extension service workers, so extension pages
* report their own storage writes here and main forwards them to the same extension's worker in the
* same session (see src/preload/browser-extension-storage-relay.ts). Workers deliver their own.
* same session (see src/preload/browser/extensions/storage/browser-extension-storage-relay.ts). Workers deliver their own.
* Sync is not relayed: main owns that area and fires its events (api/storage-sync.ts).
*/
const STORAGE_RELAY_NAMESPACE = 'orcaStorageRelay'
@@ -15,7 +15,7 @@ import type { BrowserExtensionProfileDocumentItems } from '../profile-storage/br
* writer, so every change carries exact old values. A write returns its changes to the caller,
* which fires its own listeners (a starting worker's write can reach main before its listen
* does); onChanged goes to the extension's other pages and its worker in the session.
* The preload installs it as chrome.storage.sync (src/preload/browser-extension-storage-sync.ts).
* The preload installs it as chrome.storage.sync (src/preload/browser/extensions/storage/browser-extension-storage-sync.ts).
*/
const STORAGE_SYNC_NAMESPACE = 'orcaStorageSync'
@@ -36,7 +36,7 @@ const registry = await import('../api-runtime/browser-extension-namespace-regist
const { observeBrowserExtensionWebNavigation, registerWebNavigationNamespace } =
await import('./web-navigation')
const { PRELOAD_DOCUMENT_TARGETS_NAMESPACE } =
await import('../../../../preload/browser-extension-document-targets')
await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets')
function frame(frameTreeNodeId: number, url: string, parent: FakeFrame | null = null): FakeFrame {
const created: FakeFrame = {
@@ -19,7 +19,7 @@ import { registerTabsNamespace } from './api/tabs'
import { registerWebNavigationNamespace } from './api/web-navigation'
import { registerWindowsNamespace } from './api/windows'
/** Every main-side namespace; each must also appear in src/preload/browser-extension-api-surface.ts. */
/** Every main-side namespace; each must also appear in src/preload/browser/extensions/api/browser-extension-api-surface.ts. */
export function registerBrowserExtensionNamespaces(): void {
registerWindowsNamespace()
registerTabsNamespace()
@@ -110,7 +110,7 @@ const { recordActiveBrowserPage } = await import('./browser-extension-tab-model'
const { registerTabsNamespace } = await import('../api/tabs')
const { announceRegisteredBrowserExtensionTab, observeBrowserExtensionTabLifecycle } =
await import('./browser-extension-tab-lifecycle')
await import('../../../../preload/browser-extension-document-targets')
await import('../../../../preload/browser/extensions/documents/browser-extension-document-targets')
function page(id: string, workspaceId: string, overrides: Partial<BrowserPage> = {}): BrowserPage {
return {
@@ -276,31 +276,6 @@ beforeEach(() => {
})
describe('restored browser pages without a guest are discarded tabs', () => {
it('lists every unloaded page of the caller’s profile after the loaded tabs, with a stable id', async () => {
const tabs = await query({}, [{ id: 11, url: 'https://live.test/' }])
expect(tabs.map((entry) => [entry.url, entry.discarded, entry.status, entry.index])).toEqual([
['https://live.test/', false, 'loading', 0],
['https://cold.test/', true, 'unloaded', 1],
['https://notes.test/', true, 'unloaded', 3],
['https://remote.test/', true, 'unloaded', 4]
])
const cold = tabs[1]
expect(cold).toMatchObject({ title: 'cold title', windowId: 1, active: false })
expect(cold.id).toBeGreaterThanOrEqual(discardedTabs.FIRST_DISCARDED_BROWSER_TAB_ID)
expect((await query({ discarded: true })).map((entry) => entry.id)).toEqual(
tabs.slice(1).map((entry) => entry.id)
)
expect(await call('get', [cold.id, null])).toMatchObject({ id: cold.id, discarded: true })
// Electron's native query already filtered the loaded tabs by url.
expect((await query({ url: 'https://cold.test/*' })).map((entry) => entry.id)).toEqual([
cold.id
])
// The other profile's extensions see only its own page.
expect((await query({}, [], mocks.sessions.work)).map((entry) => entry.url)).toEqual([
'https://job.test/'
])
})
it('activates through the renderer, then is replaced by the loaded guest', async () => {
const [cold] = await query({ discarded: true })
const coldId = cold.id!
@@ -28,23 +28,6 @@ afterEach(() => {
})
describe('createIntegrationStateFileCache', () => {
it('memoizes while the file is unchanged', () => {
const path = tempFile()
writeFileSync(path, '1')
let reads = 0
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => {
reads += 1
return { reads }
}
})
expect(cache.get()).toEqual({ reads: 1 })
expect(cache.get()).toEqual({ reads: 1 })
expect(reads).toBe(1)
})
it('notices a same-size atomic replacement with the original modification time', () => {
const path = tempFile()
writeFileSync(path, 'old')
@@ -63,18 +46,6 @@ describe('createIntegrationStateFileCache', () => {
expect(cache.get()).toBe('new')
})
it('distinguishes backing paths when both files are initially absent', () => {
let path = tempFile()
let reads = 0
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => ++reads
})
expect(cache.get()).toBe(1)
path = join(dir, 'another.json')
expect(cache.get()).toBe(2)
})
it('reloads when a file appears after an absent first read', () => {
const path = tempFile()
const cache = createIntegrationStateFileCache({
@@ -101,37 +72,6 @@ describe('createIntegrationStateFileCache', () => {
expect(cache.get()).toEqual({ present: false })
})
it('recovers when another process writes between the stamp and the read', () => {
const path = tempFile()
writeFileSync(path, 'v1')
let reads = 0
let writeDuringRead = false
const cache = createIntegrationStateFileCache({
filePath: () => path,
readFromDisk: () => {
reads += 1
if (writeDuringRead) {
writeDuringRead = false
writeFileSync(path, 'theirs')
}
return { body: readBody(path) }
}
})
expect(cache.get()).toEqual({ body: 'v1' })
writeFileSync(path, 'ours')
cache.invalidate()
writeDuringRead = true
// Content read after a concurrent write still carries the earlier stamp, forcing one more read.
expect(cache.get()).toEqual({ body: 'theirs' })
expect(cache.get()).toEqual({ body: 'theirs' })
expect(reads).toBe(3)
expect(cache.get()).toEqual({ body: 'theirs' })
expect(reads).toBe(3)
})
})
function readBody(path: string): string {
@@ -29,25 +29,6 @@ function createCache() {
}
describe('integration token file cache', () => {
it('bounds errors, keeps status lazy, and permits retry after keychain approval', () => {
const cache = createCache()
decrypt.mockImplementation(() => {
throw new Error('Keychain access denied')
})
for (let index = 0; index < 132; index += 1) {
const id = `credential-${index}`
writeFileSync(filePath(id), Buffer.from([0x76, 0x31, 0x30, 0xff, 0xfe]))
expect(() => cache.read(id)).toThrow('Could not decrypt')
}
expect(cache.error('credential-131')).toContain('Could not decrypt')
expect(cache.error('credential-0')).toBeUndefined()
expect(cache.has('credential-131')).toBe(true)
expect(decrypt).toHaveBeenCalledTimes(132)
decrypt.mockReturnValue('approved-token')
expect(cache.read('credential-131')).toBe('approved-token')
expect(cache.error('credential-131')).toBeUndefined()
})
it('clears an old decryption error after external replacement without prompting on status', () => {
const cache = createCache()
writeFileSync(filePath('site'), Buffer.from([0xff, 0xfe]))
@@ -153,18 +153,6 @@ describe('protected secret acknowledgements', () => {
expect(secrets.encrypt('remove', 'replacement').blob).toBe('')
})
it('does not accept a prepared update from a replaced persistence instance', () => {
const previous = new ProtectedSecretPersistence()
const current = new ProtectedSecretPersistence()
const older = prepare(previous, 'slot', 'older')
const newer = prepare(current, 'slot', 'newer')
current.commitRetentionUpdates([older, newer])
cipherState.available = false
expect(current.encrypt('slot', 'replacement').blob).toBe(ciphertext('newer'))
})
it('keeps the previous ciphertext and pending retry when a prepared save has no confirmed ack', () => {
const secrets = new ProtectedSecretPersistence()
const original = ciphertext('original')
@@ -44,34 +44,4 @@ describe('ProtectedSecretPersistence', () => {
secrets.removeRetainedBlob(slot)
expect(secrets.encrypt(slot, '')).toEqual({ blob: '', degraded: false })
})
it('keeps deferred encryption pending until its retention update commits', async () => {
const { ProtectedSecretPersistence } = await import('./protected-secret-persistence')
const secrets = new ProtectedSecretPersistence()
cipherState.available = false
secrets.encrypt('slot', 'pending')
expect(secrets.hasPendingEncryption()).toBe(true)
cipherState.available = true
const encrypted = secrets.encrypt('slot', 'pending')
expect(secrets.hasPendingEncryption()).toBe(true)
if (!encrypted.retentionUpdate) {
throw new Error('Expected a retention update')
}
secrets.commitRetentionUpdates([encrypted.retentionUpdate])
expect(secrets.hasPendingEncryption()).toBe(false)
})
it('retires a deferred empty secret without retaining a phantom retry', async () => {
const { ProtectedSecretPersistence } = await import('./protected-secret-persistence')
const secrets = new ProtectedSecretPersistence()
cipherState.available = false
secrets.encrypt('slot', 'pending')
const cleared = secrets.encrypt('slot', '')
expect(secrets.hasPendingEncryption()).toBe(true)
if (!cleared.retentionUpdate) {
throw new Error('Expected a retention update')
}
secrets.commitRetentionUpdates([cleared.retentionUpdate])
expect(secrets.hasPendingEncryption()).toBe(false)
})
})
@@ -49,8 +49,7 @@ describe('savedCredentialUnreadable', () => {
it.each([
['an empty', ''],
['a non-base64', 'not*base64!'],
['a truncated base64', 'c2VhbGVkLWhlcmU6a2V5x']
['a non-base64', 'not*base64!']
])('reports %s payload as unreadable, not sealed elsewhere', (_label, payload) => {
expect(judge(`${PREFIX}encrypted:${payload}`)).toBe('unreadable')
})
@@ -1,16 +0,0 @@
// Simulate crash without releasing ownership. Stop delivery/renewals and drain in-flight writes
// before closing test databases so pending producers cannot commit after cleanup.
import type { StructuredAgentSessionHost } from '../structured-agent-session-host'
export async function abandonStructuredAgentSessionHost(
host: StructuredAgentSessionHost
): Promise<void> {
// Stop admission before draining to prevent new delivery steps.
host['conversationDelivery'].dispose()
host['lifetime'].dispose()
await host['runtimeState'].stopLeaseRenewal()
await host['tasks'].drainAttaches()
await Promise.all([...host['sessions'].values()].map((session) => session.journal.close()))
host['sessions'].clear()
}
@@ -1,60 +0,0 @@
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { fingerprintPluginConsent } from '../../../shared/plugins/approval/plugin-consent-fingerprint'
import { pluginManifestSchema } from '../../../shared/plugins/manifest/plugin-manifest'
import { PluginContentVerifier } from '../plugin-content-integrity'
import type { ValidDiscoveredPlugin } from '../plugin-discovery'
import { PluginLanguagePackRegistry } from './plugin-language-pack-registry'
const roots: string[] = []
async function pluginWithCatalog(catalog: unknown): Promise<ValidDiscoveredPlugin> {
const rootDir = await mkdtemp(join(tmpdir(), 'orca-plugin-language-registry-'))
roots.push(rootDir)
await mkdir(join(rootDir, 'locales'))
await writeFile(join(rootDir, 'locales', 'pt-BR.json'), JSON.stringify(catalog))
const manifest = pluginManifestSchema.parse({
manifestVersion: 1,
id: 'portuguese',
publisher: 'samples',
name: 'Portuguese',
version: '1.0.0',
engines: { orca: '>=1.0.0' },
pluginApi: 1,
contributes: {
languagePacks: [{ locale: 'pt-BR', path: 'locales/pt-BR.json' }]
},
capabilities: []
})
return {
pluginKey: 'samples.portuguese',
rootDir,
manifest,
consentFingerprint: fingerprintPluginConsent(manifest),
contentHash: null,
isDev: true
}
}
afterEach(async () => {
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('PluginLanguagePackRegistry', () => {
it('loads a pack that covers protected security copy, leaving that copy in English', async () => {
const plugin = await pluginWithCatalog({
common: { save: 'Sávé' },
auto: { components: { settings: { PluginConsentDialog: { disclaimer: 'Safe' } } } }
})
const registry = new PluginLanguagePackRegistry(new PluginContentVerifier())
await registry.reconcile([plugin], () => true)
expect(registry.error(plugin.pluginKey)).toBeNull()
expect(registry.list()[0]?.catalog).toEqual({
common: { save: 'Sávé' },
auto: { components: { settings: {} } }
})
})
})
@@ -69,6 +69,18 @@ export function createProviderAccountServices(
)
store.onSettingsChanged((updates, settings) => {
void agentView.reconcile(settings)
if (updates.claudeOAuthUsageEnabled === false) {
rateLimits.discardClaudeOAuthUsage()
} else if (updates.claudeOAuthUsageEnabled === true) {
void rateLimits
.refreshClaudeForTarget(rateLimits.getState().claudeTarget)
.catch((error: unknown) => {
console.warn(
'[rate-limits] Failed to refresh Claude usage after enabling polling:',
error
)
})
}
// Auto runtime selection remains live as provider settings change.
void syncAccountRuntimeTargets(updates, settings).catch((error) =>
console.warn('[rate-limits] Failed to apply account runtime target:', error)
@@ -137,6 +149,7 @@ export function createProviderAccountServices(
apiKey: readZcodePlanApiKey() ?? ''
}))
rateLimits.setGeminiCliOAuthEnabledResolver(() => store.getSettings().geminiCliOAuthEnabled)
rateLimits.setClaudeOAuthUsageEnabledResolver(() => store.getSettings().claudeOAuthUsageEnabled)
// Reuse the meter switch so hidden Antigravity usage does not spawn agy.
rateLimits.setAntigravityUsageEnabledResolver(() =>
store.getUI().statusBarItems.includes('antigravity')
@@ -30,6 +30,14 @@ export function makeClaudeUsageResult(
}
}
// Not idle: the meter draws idle as pending, and nothing here will settle it.
export function claudeOAuthUsageDisabledResult(): ProviderRateLimits {
return makeClaudeUsageResult('unavailable', 'Usage appears when a Claude session runs.', {
failureKind: 'usage-unavailable',
attemptedSources: []
})
}
// Account rows explain host/profile failures; usage keeps its generic message.
export function claudeUsageUnavailable(): ProviderRateLimits {
return makeClaudeUsageResult('error', 'Claude usage is unavailable right now.', {
@@ -19,6 +19,7 @@ import type {
OpenCodeGoRateLimitConfig,
MiniMaxRateLimitConfig,
AntigravityUsageEnabledResolver,
ClaudeOAuthUsageEnabledResolver,
MuseUsageEnabledResolver,
ZcodePlanRateLimitConfig,
GeminiCliOAuthEnabledResolver,
@@ -73,6 +74,27 @@ export class RateLimitService extends RateLimitServiceAccountRefresh {
this.geminiCliOAuthEnabledResolver = resolver
}
setClaudeOAuthUsageEnabledResolver(resolver: ClaudeOAuthUsageEnabledResolver): void {
this.claudeOAuthUsageEnabledResolver = resolver
}
// Retain only readings actually received from the terminal feed.
discardClaudeOAuthUsage(): void {
this.claudeUsageAbortController.abort()
this.claudeUsageAbortController = new AbortController()
this.claudeFetchGeneration += 1
this.inactiveClaudeAccountsGeneration += 1
this.inactiveClaudeCache.clear()
this.inactiveClaudeFetching.clear()
this.lastInactiveClaudeFetchAt = 0
this.lastClaudeCheckCompletedAt = null
this.activeFailureStreakByProvider.claude = 0
this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() })
if (!this.lastClaudeAuthSnapshot) {
void this.fetchClaudeOnly({ force: true })
}
}
setAntigravityUsageEnabledResolver(resolver: AntigravityUsageEnabledResolver): void {
this.antigravityUsageEnabledResolver = resolver
}
@@ -162,6 +184,10 @@ export class RateLimitService extends RateLimitServiceAccountRefresh {
void this.fetchAll()
} else {
this.scheduleDeferredStartupRefresh()
// Passive terminal usage needs account attribution even without a usage viewer.
if (!this.isClaudeOAuthUsageEnabled()) {
void this.fetchClaudeOnly({ force: true })
}
}
this.startTimer()
}
@@ -57,6 +57,9 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna
provider: 'claude' | 'codex',
options: { notWithinMs?: number } = {}
): boolean {
if (provider === 'claude' && !this.isClaudeOAuthUsageEnabled()) {
return false
}
const limits = this.state[provider]
const now = Date.now()
if (this.isFetching || this.isRetryAfterActive(limits)) {
@@ -230,6 +233,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna
this.activeFailureStreakByProvider.claude = 0
// Outgoing statusline posts must not land on the incoming account during the switch.
this.lastClaudeAuthSnapshot = null
this.liveClaudeUsage = null
this.usageReadingAccounts.claude = undefined
this.lastInactiveClaudeFetchAt = 0
this.updateState({
...this.state,
@@ -249,6 +254,8 @@ export abstract class RateLimitServiceAccountRefresh extends RateLimitServiceIna
if (targetChanged) {
// Outgoing target posts must not land on the incoming target during the switch.
this.lastClaudeAuthSnapshot = null
this.liveClaudeUsage = null
this.usageReadingAccounts.claude = undefined
}
this.updateState({
...this.state,
@@ -15,10 +15,24 @@ import {
isStaleClaudeUsageWindow,
mapClaudeUsageWindow
} from '../providers/claude/claude-usage-window'
import { claudeOAuthUsageDisabledResult } from '../providers/claude/claude-usage-result'
import { readUserClaudeConfigDir } from '../../claude-accounts/profiles/claude-profile-paths'
import { getClaudeProfileRouter } from '../../claude-accounts/profiles/routing/claude-profile-installed-router'
export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchTargets {
protected isClaudeOAuthUsageEnabled(): boolean {
return this.claudeOAuthUsageEnabledResolver?.() ?? true
}
protected claudeUsageFetchSignal(signal: AbortSignal): AbortSignal {
return AbortSignal.any([signal, this.claudeUsageAbortController.signal])
}
protected claudeUsageWithoutOAuth(): ProviderRateLimits {
const live = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, Date.now()) : null
return live?.session || live?.weekly ? live : claudeOAuthUsageDisabledResult()
}
protected getMiniMaxCredentialError(message: string): ProviderRateLimits {
return {
provider: 'minimax',
@@ -44,6 +58,12 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT
}
}
protected claudeStateAtCycleStart(limits: ProviderRateLimits | null): ProviderRateLimits {
return this.isClaudeOAuthUsageEnabled()
? this.withFetchingStatus(limits, 'claude')
: this.claudeUsageWithoutOAuth()
}
// Retry-After remains binding even when live posts restore ok display; early polls waste budget and prolong 429s.
protected isRetryAfterActive(limits: ProviderRateLimits | null): boolean {
return Boolean(limits?.usageMetadata?.retryAtMs && limits.usageMetadata.retryAtMs > Date.now())
@@ -70,6 +90,9 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT
fresh: ProviderRateLimits,
previous: ProviderRateLimits | null
): ProviderRateLimits {
if (!this.isClaudeOAuthUsageEnabled()) {
return this.claudeUsageWithoutOAuth()
}
this.lastClaudeCheckCompletedAt = fresh.updatedAt
// Failed OAuth must preserve newer live display while forwarding Retry-After to the poll gate.
const current = this.state.claude
@@ -94,15 +117,23 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT
) {
return
}
this.lastClaudeAuthSnapshot = {
const snapshot = {
// System Default uses the user config folder without injecting a managed one.
configDir: normalizeClaudeConfigDir(
authPreparation?.envPatch.CLAUDE_CONFIG_DIR ??
getClaudeProfileRouter()?.userConfigDir() ??
readUserClaudeConfigDir(process.env)
),
home: authPreparation?.configDir,
provenance: authPreparation?.provenance ?? 'system'
}
if (
snapshot.configDir !== this.lastClaudeAuthSnapshot?.configDir ||
snapshot.provenance !== this.lastClaudeAuthSnapshot?.provenance
) {
this.liveClaudeUsage = null
}
this.lastClaudeAuthSnapshot = snapshot
}
ingestLiveClaudeRateLimits(event: ClaudeStatusLineRateLimits): void {
@@ -155,6 +186,26 @@ export abstract class RateLimitServiceFetchPolicy extends RateLimitServiceFetchT
) {
return
}
const priorLive = this.liveClaudeUsage ? withoutResetWindows(this.liveClaudeUsage, now) : null
this.liveClaudeUsage = {
provider: 'claude',
session: freshSession ?? priorLive?.session ?? null,
weekly: freshWeekly ?? priorLive?.weekly ?? null,
updatedAt: now,
error: null,
status: 'ok',
usageMetadata: {
source: 'live-session',
lastSuccessfulSource: 'live-session',
authProvenance: snapshot.provenance
}
}
this.rememberUsageReadingAccount(
'claude',
this.claudeFetchTarget,
snapshot.home,
snapshot.provenance
)
if (
previous?.status === 'ok' &&
previous.usageMetadata?.source === 'live-session' &&
@@ -153,7 +153,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ
this.updateState({
...previousState,
claude: this.withFetchingStatus(previousState.claude, 'claude'),
claude: this.claudeStateAtCycleStart(previousState.claude),
// A gated slot makes no attempt and cannot settle a fetching chip.
codex: codexFetchGated
? codexStateBeforeFetch
@@ -220,7 +220,9 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ
// Live display does not waive automated Retry-After gates.
const claudeFetchGated =
!options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude)
!this.isClaudeOAuthUsageEnabled() ||
claudeGeneration !== this.claudeFetchGeneration ||
(!options?.force && this.shouldSkipAutomatedFetch('claude', previousState.claude))
const [claudeResult, codexResult, geminiResult, opencodeGoResult, kimiResult, miniMaxResult] =
await Promise.allSettled([
@@ -231,7 +233,7 @@ export abstract class RateLimitServiceFullCyclePreparation extends RateLimitServ
allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation),
allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(),
networkProxySettings: this.networkProxySettingsResolver?.(),
signal
signal: this.claudeUsageFetchSignal(signal)
}),
codexFetchGated
? Promise.resolve(previousState.codex as ProviderRateLimits)
@@ -6,6 +6,9 @@ import { delayUnlessAborted } from '../../../shared/abort-aware-delay'
export abstract class RateLimitServiceInactiveAccounts extends RateLimitServicePolling {
async fetchInactiveClaudeAccountsOnOpen(): Promise<void> {
if (!this.isClaudeOAuthUsageEnabled()) {
return
}
if (Date.now() - this.lastInactiveClaudeFetchAt < INACTIVE_FETCH_DEBOUNCE_MS) {
return
}
@@ -21,7 +24,7 @@ export abstract class RateLimitServiceInactiveAccounts extends RateLimitServiceP
}
const fetchGeneration = this.inactiveClaudeAccountsGeneration
const controller = this.beginFetchCycle()
const signal = controller.signal
const signal = this.claudeUsageFetchSignal(controller.signal)
for (const account of accounts) {
this.inactiveClaudeFetching.add(account.id)
@@ -87,6 +87,7 @@ export abstract class RateLimitServicePolling extends RateLimitServiceFetchQueue
const museEnabled = this.museUsageEnabledResolver?.() ?? true
return Object.entries(byProvider)
.filter(([provider]) => provider !== 'muse' || museEnabled)
.filter(([provider]) => provider !== 'claude' || this.isClaudeOAuthUsageEnabled())
.map(([provider, limits]) => ({
provider: provider as ActiveRateLimitProvider,
limits
@@ -94,10 +94,15 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul
// Why: capture before the resolver await so an account switch during it invalidates both the snapshot and the state apply.
const claudeGeneration = this.claudeFetchGeneration
const claudeAuthPreparation = await this.claudeAuthPreparationResolver?.(claudeTarget)
if (signal.aborted) {
if (signal.aborted || claudeGeneration !== this.claudeFetchGeneration) {
return
}
this.rememberClaudeAuthSnapshot(claudeAuthPreparation, claudeGeneration, claudeTarget)
// After the snapshot: statusLine posts are dropped until one names the selected account.
if (!this.isClaudeOAuthUsageEnabled()) {
this.updateState({ ...this.state, claude: this.claudeUsageWithoutOAuth() })
return
}
const claudeProvenance = claudeAuthPreparation?.provenance ?? 'system'
const previousState = this.state
@@ -111,7 +116,7 @@ export abstract class RateLimitServiceProviderCycles extends RateLimitServiceFul
allowPtyFallback: this.shouldAllowClaudePtyFallback(claudeAuthPreparation),
allowUsagePanelSupplement: this.shouldAllowClaudeUsagePanelSupplement(),
networkProxySettings: this.networkProxySettingsResolver?.(),
signal
signal: this.claudeUsageFetchSignal(signal)
}).catch((err): ProviderRateLimits => ({
provider: 'claude',
session: null,
@@ -2,10 +2,12 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { ProviderRateLimits } from '../../../shared/rate-limit-types'
import { RateLimitService } from './rate-limit-service'
import { fetchActiveClaudeRateLimits } from '../providers/claude/claude-active-usage-fetch'
import { fetchInactiveClaudeAccountUsage } from '../providers/claude/claude-managed-account-usage'
import { fetchCodexRateLimits } from '../providers/codex/codex-fetcher'
import {
deferred,
flushMicrotasks,
mockFreshBackgroundProviderFetches,
okProvider,
resetRateLimitProviderMocks
} from './rate-limit-service-test-harness'
@@ -95,4 +97,213 @@ describe('RateLimitService', () => {
await flushMicrotasks(60)
expect(service.getState().claude?.session?.usedPercent).toBe(55)
})
it('keeps live Claude usage through refreshes without reading OAuth usage when disabled', async () => {
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
service.setClaudeOAuthUsageEnabledResolver(() => false)
service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }])
let home = '/claude/account-a'
service.setClaudeAuthPreparationResolver(async () => ({
configDir: home,
envPatch: { CLAUDE_CONFIG_DIR: home },
provenance: home
}))
service.start({ fetchImmediately: false })
await flushMicrotasks(20)
service.stop()
expect(service.getState().claude).toMatchObject({
session: null,
weekly: null,
status: 'unavailable'
})
service.ingestLiveClaudeRateLimits({
configDir: '/claude/account-a',
fiveHour: { used_percentage: 33 },
sevenDay: { used_percentage: 62 }
})
await service.refreshClaudeForTarget()
await service.refresh()
await service.fetchInactiveClaudeAccountsOnOpen()
expect(service.getState().claude).toMatchObject({
session: { usedPercent: 33 },
weekly: { usedPercent: 62 },
status: 'ok',
usageMetadata: { source: 'live-session' }
})
expect(service.getState().inactiveClaudeAccounts).toEqual([])
expect(service.usageReadingAccount('claude')).toEqual({
home: '/claude/account-a',
provenance: '/claude/account-a'
})
expect(service.requestUsageReading('claude')).toBe(false)
expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalled()
expect(fetchInactiveClaudeAccountUsage).not.toHaveBeenCalled()
home = '/claude/account-b'
await service.refreshForClaudeAccountChange('outgoing')
expect(service.getState().claude?.session).toBeNull()
expect(service.getState().claude?.status).toBe('unavailable')
service.ingestLiveClaudeRateLimits({
configDir: '/claude/account-b',
fiveHour: { used_percentage: 12 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(12)
expect(service.usageReadingAccount('claude')).toEqual({
home: '/claude/account-b',
provenance: '/claude/account-b'
})
})
it('cancels pending Claude usage and rejects its reply even after polling is enabled again', async () => {
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
let enabled = true
service.setClaudeOAuthUsageEnabledResolver(() => enabled)
const started = deferred<AbortSignal | undefined>()
const reply = deferred<ProviderRateLimits>()
vi.mocked(fetchActiveClaudeRateLimits).mockImplementationOnce((options) => {
started.resolve(options?.signal)
return reply.promise
})
const refresh = service.refresh()
const signal = await started.promise
enabled = false
service.discardClaudeOAuthUsage()
expect(signal?.aborted).toBe(true)
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour: { used_percentage: 41 },
sevenDay: null
})
enabled = true
reply.resolve(okProvider('claude', 90))
await refresh
expect(service.getState().claude).toMatchObject({
session: { usedPercent: 41 },
status: 'ok',
usageMetadata: { source: 'live-session' }
})
})
it('retains only terminal-observed windows when disabling OAuth-enriched usage', async () => {
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
let enabled = true
service.setClaudeOAuthUsageEnabledResolver(() => enabled)
vi.mocked(fetchActiveClaudeRateLimits).mockResolvedValueOnce({
...okProvider('claude', 20),
weekly: { usedPercent: 50, windowMinutes: 10080, resetsAt: null, resetDescription: null },
fableWeekly: {
usedPercent: 70,
windowMinutes: 10080,
resetsAt: null,
resetDescription: null
},
extraUsage: {
unit: 'credits',
enabled: true,
balance: 100,
unlimited: false,
disabledReason: null,
resetsAt: null
}
})
await service.refresh()
service.ingestLiveClaudeRateLimits({
configDir: null,
fiveHour: { used_percentage: 35 },
sevenDay: null
})
expect(service.getState().claude?.weekly?.usedPercent).toBe(50)
enabled = false
service.discardClaudeOAuthUsage()
await service.refresh()
expect(service.getState().claude).toMatchObject({
session: { usedPercent: 35 },
weekly: null,
usageMetadata: { source: 'live-session' }
})
expect(service.getState().claude?.fableWeekly).toBeFalsy()
expect(service.getState().claude?.extraUsage).toBeFalsy()
await service.refreshForClaudeAccountChange('outgoing')
expect(service.getState().claude?.session).toBeNull()
})
it('discards pending inactive-account usage when polling is disabled', async () => {
const service = new RateLimitService()
let enabled = true
service.setClaudeOAuthUsageEnabledResolver(() => enabled)
service.setInactiveClaudeAccountsResolver(() => [{ id: 'other' }, { id: 'another' }])
const started = deferred<AbortSignal | undefined>()
const reply = deferred<ProviderRateLimits>()
vi.mocked(fetchInactiveClaudeAccountUsage).mockImplementationOnce((_account, options) => {
started.resolve(options?.signal)
return reply.promise
})
const refresh = service.fetchInactiveClaudeAccountsOnOpen()
const signal = await started.promise
enabled = false
service.discardClaudeOAuthUsage()
expect(signal?.aborted).toBe(true)
enabled = true
reply.resolve(okProvider('claude', 90))
await refresh
expect(service.getState().inactiveClaudeAccounts).toEqual([])
expect(service.getState().claude).toMatchObject({
session: null,
weekly: null,
status: 'unavailable'
})
})
it.each(['all', 'claude'] as const)(
'does not revive a canceled %s request still preparing account attribution',
async (cycle) => {
mockFreshBackgroundProviderFetches()
const service = new RateLimitService()
let enabled = true
service.setClaudeOAuthUsageEnabledResolver(() => enabled)
const oldAuth = { configDir: '/claude/old', envPatch: {}, provenance: 'old' }
const preparation = deferred<typeof oldAuth>()
service.setClaudeAuthPreparationResolver(
vi
.fn()
.mockReturnValueOnce(preparation.promise)
.mockResolvedValue({
configDir: '/claude/current',
envPatch: { CLAUDE_CONFIG_DIR: '/claude/current' },
provenance: 'current'
})
)
const refresh = cycle === 'all' ? service.refresh() : service.refreshClaudeForTarget()
enabled = false
service.discardClaudeOAuthUsage()
enabled = true
preparation.resolve(oldAuth)
await refresh
expect(fetchActiveClaudeRateLimits).not.toHaveBeenCalledWith(
expect.objectContaining({ authPreparation: oldAuth })
)
service.ingestLiveClaudeRateLimits({
configDir: '/claude/current',
fiveHour: { used_percentage: 15 },
sevenDay: null
})
expect(service.getState().claude?.session?.usedPercent).toBe(15)
expect(service.usageReadingAccount('claude')).toEqual({
home: '/claude/current',
provenance: 'current'
})
}
)
})
@@ -17,6 +17,7 @@ import {
type OpenCodeGoRateLimitConfig,
type MiniMaxRateLimitConfig,
type AntigravityUsageEnabledResolver,
type ClaudeOAuthUsageEnabledResolver,
type MuseUsageEnabledResolver,
type ZcodePlanRateLimitConfig,
type GeminiCliOAuthEnabledResolver,
@@ -90,10 +91,16 @@ export abstract class RateLimitServiceState {
protected fetchIdleResolvers: (() => void)[] = []
protected codexFetchGeneration = 0
protected claudeFetchGeneration = 0
protected claudeUsageAbortController = new AbortController()
protected liveClaudeUsage: ProviderRateLimits | null = null
// Why: cached display receipts cannot establish when the selected account was last checked.
protected lastClaudeCheckCompletedAt: number | null = null
// Capture account attribution once per cycle instead of rerunning auth preparation on every post.
protected lastClaudeAuthSnapshot: { configDir: string | null; provenance: string } | null = null
protected lastClaudeAuthSnapshot: {
configDir: string | null
home: string | undefined
provenance: string
} | null = null
/** Where the applied host-runtime Claude/Codex readings were taken. */
protected usageReadingAccounts: Partial<
Record<'claude' | 'codex', { home: string; provenance: string }>
@@ -122,6 +129,7 @@ export abstract class RateLimitServiceState {
protected miniMaxConfigResolver: (() => MiniMaxRateLimitConfig) | null = null
protected zcodePlanConfigResolver: (() => ZcodePlanRateLimitConfig) | null = null
protected geminiCliOAuthEnabledResolver: GeminiCliOAuthEnabledResolver | null = null
protected claudeOAuthUsageEnabledResolver: ClaudeOAuthUsageEnabledResolver | null = null
protected antigravityUsageEnabledResolver: AntigravityUsageEnabledResolver | null = null
protected antigravityFetchTarget: LocalAccountRuntimeTarget = { runtime: 'host', wslDistro: null }
protected antigravityAccountUsageRecorder: AntigravityAccountUsageRecorder | null = null
@@ -62,6 +62,7 @@ export type ZcodePlanResolvedConfig = {
export type GeminiCliOAuthEnabledResolver = () => boolean
export type AntigravityUsageEnabledResolver = () => boolean
export type ClaudeOAuthUsageEnabledResolver = () => boolean
export type MuseUsageEnabledResolver = () => boolean
export type ActiveRateLimitProvider = ProviderRateLimits['provider']
export type ActiveProviderState = {
@@ -71,7 +71,6 @@ describe('prepareLocalCommitMessageAgentEnv', () => {
ANTHROPIC_AUTH_TOKEN: 'chosen-token'
}
})
expect(await prepareLocalCommitMessageAgentEnv('custom', undefined)).toEqual({ ok: true })
})
it('hydrates OpenCode config dir from shell startup files for headless generation', async () => {
@@ -89,21 +88,6 @@ describe('prepareLocalCommitMessageAgentEnv', () => {
})
})
it('hydrates Pi agent dir from shell startup files for headless generation', async () => {
const home = makeHome()
delete process.env.PI_CODING_AGENT_DIR
writeFileSync(join(home, '.zshrc'), 'export PI_CODING_AGENT_DIR="$HOME/.config/pi-agent"\n')
const result = await prepareLocalCommitMessageAgentEnv('pi', undefined)
expect(result).toEqual({
ok: true,
env: expect.objectContaining({
PI_CODING_AGENT_DIR: `${home}/.config/pi-agent`
})
})
})
// STA-4422: failed managed-home preparation must not fall through to the user's real account while UI shows a managed account.
it('strips a nested-Orca CODEX_HOME override when the launch resolves to the real home', async () => {
@@ -2,10 +2,7 @@ import { spawn } from 'node:child_process'
import type * as ChildProcess from 'node:child_process'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { generateCommitMessageFromContext } from '../commit-message-text-generation'
import {
createChildTerminationExpectation,
withPlatform
} from './commit-message-text-generation-test-harness'
import { createChildTerminationExpectation } from './commit-message-text-generation-test-harness'
const { terminateWindowsProcessTreeMock } = vi.hoisted(() => ({
terminateWindowsProcessTreeMock: vi.fn(async () => {})
@@ -84,32 +81,4 @@ describe('generateCommitMessageFromContext on the Windows direct-child path', ()
})
await expectChildTerminated(child)
})
it('rejects unsafe argv prompts for Windows batch-script agent commands', async () => {
await withPlatform('win32', async () => {
const result = await generateCommitMessageFromContext(
{
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello & goodbye'
},
{
agentId: 'custom',
model: '',
customAgentCommand: 'C:/tools/agent.cmd {prompt}'
},
{
kind: 'local',
cwd: 'C:\\repo'
}
)
expect(result).toMatchObject({
success: false,
error:
"C:/tools/agent.cmd runs through a Windows batch script that cannot take the multi-line prompt as an argument. Point Settings at the agent's executable, or use a custom command without {prompt} so Orca sends the prompt on stdin."
})
expect(spawnMock).not.toHaveBeenCalled()
})
})
})
@@ -3,46 +3,6 @@ import { describe, expect, it } from 'vitest'
import { generateCommitMessageFromContext } from '../commit-message-text-generation'
describe('generateCommitMessageFromContext', () => {
it('uses a prepared remote execution plan instead of running git on the remote side', async () => {
const result = await generateCommitMessageFromContext(
{
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
},
{
agentId: 'custom',
model: '',
customAgentCommand: 'agent --message {prompt}'
},
{
kind: 'remote',
cwd: '/repo',
missingBinaryLocation: 'remote PATH',
execute: async (plan, cwd, timeoutMs) => {
expect(cwd).toBe('/repo')
expect(timeoutMs).toBe(60_000)
expect(plan.binary).toBe('agent')
expect(plan.args).toHaveLength(2)
expect(plan.args[0]).toBe('--message')
expect(plan.args[1]).toContain('Staged files:\nM\tREADME.md')
return {
stdout: 'Add README note.\n',
stderr: '',
exitCode: 0,
timedOut: false
}
}
}
)
expect(result).toEqual({
success: true,
message: 'Add README note',
agentLabel: 'agent'
})
})
it('sanitizes remote execution transport failures', async () => {
const result = await generateCommitMessageFromContext(
{
@@ -47,8 +47,7 @@ describe.runIf(process.platform !== 'win32')('chat naming CLI discovery', () =>
it.each([
['./node_modules/.bin:EMPTY', 'node_modules/.bin'],
[':EMPTY', '.'],
['EMPTY:', '.']
[':EMPTY', '.']
])('resolves recipe PATH %s from the workspace before global installs', async (path, folder) => {
const home = mkdtempSync(join(tmpdir(), 'orca-naming-recipe-path-'))
homes.push(home)
@@ -1,93 +0,0 @@
import 'node:events'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as RunProcess from '@orca/process-host'
import type { ProcessSpec } from '@orca/process-host/process-spec'
import '../../provider-process/provider-process-supervisor'
import { generateCommitMessageFromContext } from '../commit-message-text-generation'
import './commit-message-text-generation-test-harness'
import './source-control-agent-launch'
const { spawnProcessMock } = vi.hoisted(() => ({ spawnProcessMock: vi.fn() }))
vi.mock('@orca/process-host', async (importOriginal) => {
const actual = await importOriginal<typeof RunProcess>()
spawnProcessMock.mockImplementation(actual.spawnProcess)
return { ...actual, spawnProcess: spawnProcessMock }
})
function lastSpawnSpec(): ProcessSpec {
return spawnProcessMock.mock.calls.at(-1)![0]
}
function decodedSupervisorSpec(spec: ProcessSpec): Record<string, unknown> {
return JSON.parse(Buffer.from(spec.env!.ORCA_PROVIDER_SUPERVISOR_SPEC!, 'base64').toString())
}
const folder = mkdtempSync(join(tmpdir(), 'orca-agent-launch-'))
afterAll(() => rmSync(folder, { recursive: true, force: true }))
beforeEach(() => {
spawnProcessMock.mockClear()
})
describe.runIf(process.platform !== 'win32')('supervised agent processes', () => {
it('passes the stdin end through so the agent can answer its request', async () => {
const agent = join(folder, 'echo-agent.cjs')
writeFileSync(
agent,
`let prompt = ''
process.stdin.on('data', (chunk) => (prompt += chunk))
process.stdin.on('end', () => setTimeout(() => console.log(prompt.includes('README') ? 'Update README' : 'no prompt'), 1200))
`
)
await expect(
generateCommitMessageFromContext(
{
branch: 'main',
stagedSummary: 'M README.md',
stagedPatch: '+test'
},
{
agentId: 'custom',
model: '',
customAgentCommand: `"${process.execPath}" "${agent}"`
},
{ kind: 'local', cwd: folder }
)
).resolves.toMatchObject({ success: true, message: 'Update README' })
expect(lastSpawnSpec().program).toBe(process.execPath)
expect(decodedSupervisorSpec(lastSpawnSpec())).toMatchObject({
lifetime: 'one-shot'
})
})
it('drops the agent session that launched Orca but keeps assignments in the command', async () => {
const agent = join(folder, 'session-agent.cjs')
writeFileSync(
agent,
`process.stdin.resume()
process.stdin.on('end', () => console.log('Thread ' + (process.env.CODEX_THREAD_ID ?? 'unset') + ', effort ' + process.env.CLAUDE_EFFORT))
`
)
vi.stubEnv('CODEX_THREAD_ID', 'parent-thread')
try {
await expect(
generateCommitMessageFromContext(
{ branch: 'main', stagedSummary: 'M README.md', stagedPatch: '+test' },
{
agentId: 'custom',
model: '',
customAgentCommand: `CLAUDE_EFFORT=low "${process.execPath}" "${agent}"`
},
{ kind: 'local', cwd: folder }
)
).resolves.toMatchObject({ success: true, message: 'Thread unset, effort low' })
} finally {
vi.unstubAllEnvs()
}
})
})
@@ -8,15 +8,6 @@ const ESC = String.fromCharCode(27)
const BEL = String.fromCharCode(7)
describe('captureAgentGenerationFailureOutput', () => {
it('returns null when both streams are blank', () => {
expect(captureAgentGenerationFailureOutput('Pi', 1, ' \n', '\t')).toBeNull()
})
it('keeps short streams verbatim', () => {
const capture = captureAgentGenerationFailureOutput('Pi', 1, 'out', 'err')
expect(capture).toEqual({ label: 'Pi', exitCode: 1, stdout: 'out', stderr: 'err' })
})
it('bounds an oversized stream to its head and tail with an omission marker', () => {
const oversized = `${'h'.repeat(20_000)}${'m'.repeat(40_000)}${'t'.repeat(50_000)}`
const capture = captureAgentGenerationFailureOutput('Pi', 1, '', oversized)
@@ -29,30 +20,6 @@ describe('captureAgentGenerationFailureOutput', () => {
})
describe('formatAgentGenerationFailureOutputForDisplay', () => {
it('renders a header plus the streams that had content, stderr first', () => {
const text = formatAgentGenerationFailureOutputForDisplay({
label: 'Pi',
exitCode: 1,
stdout: 'partial result',
stderr: 'No API key found for github-copilot.'
})
expect(text).toBe(
'Pi exited with code 1.\n\n[stderr]\nNo API key found for github-copilot.\n\n[stdout]\npartial result'
)
})
it('omits a blank stream section and reports an unknown exit code', () => {
const text = formatAgentGenerationFailureOutputForDisplay({
label: 'Claude',
exitCode: null,
stdout: 'Not logged in · Please run /login',
stderr: ' '
})
expect(text).toBe(
'Claude exited with code unknown.\n\n[stdout]\nNot logged in · Please run /login'
)
})
it('strips ANSI, OSC, and bidi-override characters while keeping line structure', () => {
const text = formatAgentGenerationFailureOutputForDisplay({
label: 'Pi',
@@ -2,37 +2,6 @@ import { describe, expect, it } from 'vitest'
import { generateCommitMessageFromContext } from '../commit-message-text-generation'
describe('generateCommitMessageFromContext', () => {
it('exposes raw CLI failure output only after path sanitization', async () => {
const result = await generateCommitMessageFromContext(
{
branch: 'main',
stagedSummary: 'M\tREADME.md',
stagedPatch: '+hello'
},
{
agentId: 'custom',
model: '',
customAgentCommand: 'agent'
},
{
kind: 'remote',
cwd: '/repo',
missingBinaryLocation: 'remote PATH',
execute: async () => ({
stdout: 'You are generating a single git commit message for /secret/repo',
stderr: 'raw failure output with /Users/thebr/My Repo/secret/file.ts',
exitCode: 1,
timedOut: false
})
}
)
expect(result).toMatchObject({
success: false,
error: 'agent CLI command failed with code 1: raw failure output with [path]'
})
})
it('formats nonzero exit failures with extracted sanitized CLI details', async () => {
const result = await generateCommitMessageFromContext(
{
@@ -27,7 +27,6 @@ const run = (message: string) => `error: failed to run prompt: ${message}\nSee l
const network = run('provider.connection_error: getaddrinfo ENOTFOUND private-host')
const agentOptions =
/^Kimi received conflicting or repeated agent options\. Keep a single --agent or --agent-file option in the generation recipe or CLI arguments, then retry\.$/
const credentials = /credentials.*execution host.*configure.*sign in/
const parser =
/^Kimi rejected an option or argument\. Correct the generation recipe or CLI arguments, then retry\.$/
const delimiters = "private-x' argument '".repeat(12)
@@ -36,36 +35,11 @@ const delimiters = "private-x' argument '".repeat(12)
it.each([
['', occupied, realKimiOccupiedOutput, 4],
[run('unrelated private-prose'), occupied, `${earlier}\n${realKimiOccupiedOutput}`, 4],
[run('Session "private-session" not found.'), /find.*session.*existing session.*new one/],
[
run('Session "private-session" was created under a different directory.'),
/another directory.*Resume it there.*workspace/
],
[
run('no provider configured; complete onboarding via /login or the providers endpoint'),
credentials
],
[
run(
'Provider "private-provider" declares api_key_env = "PRIVATE_ENV" in config.toml, but the environment variable is not set or is empty.'
),
/credential environment variable.*Set it.*execution host/
],
[
run('model private-model does not resolve to a configured provider'),
/usable model.*configure or select/
],
[run('Prompt hook blocked the request.'), /hook blocked.*Review.*hooks.*retry/],
[run('Prompt turn ended with reason: cancelled'), /cancelled.*Try again/],
[
run('provider.auth_error: private-provider prose'),
/authenticate.*Sign in.*credentials.*retry/,
'{broken'
],
[run('provider.rate_limit: private-provider prose'), /limit.*Wait.*reduce/],
[run('Provider safety policy blocked the response.'), /blocked.*Revise.*prompt.*configuration/],
[run('context.overflow: private-provider prose'), /context.*Shorten.*new session/],
[run('config.invalid: private-provider prose'), /invalid configuration.*Check.*model.*provider/],
[network, /connect.*network.*retry/],
[network, /connect.*network.*MagicDNS/, '', 1, true],
...[
@@ -84,17 +58,6 @@ it.each([
[run("unknown option '--private-flag'"), unknown, '{"type":"error","code":"unknown.code"}'],
[`error: option '${delimiters}tail`, unknown],
[`error: option '${delimiters}value' is invalid. provider.auth_error: private-prose`, parser],
['error: Login required\n\nmessage:\nprivate-prose\nSee log: private-path', credentials],
['error: Prompt cannot be empty.', /empty prompt.*recipe.*CLI arguments/],
[
'error: Cannot combine --prompt with --auto.',
/conflicting.*--prompt.*--auto.*recipe.*arguments/
],
[
'error: Cannot combine --agent/--agent-file with --session/--continue: the agent is bound at session creation and the bound agent is restored automatically on resume.',
/cannot change the agent.*Remove.*override.*new session/
],
['error: Cannot use --session without an id in prompt mode.', /session id.*recipe.*arguments/],
["hook narration error: unknown option '--private-flag'", unknown],
['', /Kimi.*interrupted.*Try again/, '', null],
['', invalid, realKimiOccupiedOutput, 0],
@@ -1,18 +1,9 @@
import { spawnProcess } from '@orca/process-host'
import * as agentSpecs from '../../../shared/source-control/ai/generation/commit-message-agent-spec'
import type { ResolvedSourceControlAiGenerationParams } from '../../../shared/source-control/ai/source-control-ai-operation-resolution'
import type { SpawnSourceControlAgent } from '../source-control-text-generation-types'
import {
generateCommitMessage,
generatePullRequestFields,
generateBranchName
} from '../requests/source-control-text-generation-requests'
import { generateConversationName } from '../requests/conversation-name-generation-request'
import { generateJiraIssueSummaryFromContext } from '../requests/jira-issue-summary-text-generation'
import { generateCommitMessage } from '../requests/source-control-text-generation-requests'
import { existsSync, mkdtempSync, readFileSync } from 'node:fs'
import { rm } from 'node:fs/promises'
import type * as FsPromises from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
@@ -29,13 +20,6 @@ vi.mock('../../pty/process-retirement/windows-process-tree-kill', () => ({
terminateWindowsProcessTree: vi.fn(async () => true)
}))
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof FsPromises>()
return { ...actual, rm: vi.fn(actual.rm) }
})
const actualFs = await vi.importActual<typeof FsPromises>('node:fs/promises')
afterEach(() => vi.useRealTimers())
// OMP 17.0.5 recorded stdin-only execution: exit 0, empty stdout/stderr, no submitted prompt.
@@ -137,96 +121,6 @@ const commitContext = {
stagedPatch: '+ Trace lighthouse signal'
}
type Consumer = {
label: string
run(
params: ResolvedSourceControlAiGenerationParams,
spawnAgent: SpawnSourceControlAgent
): Promise<unknown>
output: string
expected: object
}
const consumers: Consumer[] = [
{
label: 'commit',
run: (params, spawnAgent) =>
generateCommitMessage({ context: commitContext, params, target: contractTarget, spawnAgent }),
output: 'Trace lighthouse signal.\n\nPreserve request bytes\n',
expected: { message: 'Trace lighthouse signal\n\nPreserve request bytes' }
},
{
label: 'PR fields',
run: (params, spawnAgent) =>
generatePullRequestFields({
context: {
branch: 'feature',
base: 'main',
branchChangedByPreparation: true,
currentTitle: '',
currentBody: '',
currentDraft: false,
commitSummary: 'Trace lighthouse signal',
changeSummary: 'signal.ts',
patch: '+ Trace lighthouse signal'
},
params,
target: contractTarget,
spawnAgent
}),
output: JSON.stringify({
base: 'main',
title: 'Trace lighthouse signal.',
body: 'Preserve request bytes\n',
draft: true
}),
expected: {
fields: {
base: 'main',
title: 'Trace lighthouse signal',
body: 'Preserve request bytes',
draft: true
},
branchChangedByPreparation: true
}
},
{
label: 'branch slug / folder title',
run: (params, spawnAgent) =>
generateBranchName({
context: { firstPrompt: 'Trace lighthouse signal' },
params,
target: contractTarget,
spawnAgent
}),
output: 'Trace Lighthouse Signal!',
expected: { slug: 'trace-lighthouse-signal' }
},
{
label: 'conversation name',
run: (params, spawnAgent) =>
generateConversationName({
context: { firstPrompt: 'Trace lighthouse signal' },
params,
target: contractTarget,
spawnAgent
}),
output: '# Title: "Trace lighthouse signal"\nextra commentary',
expected: { name: 'Trace lighthouse signal' }
},
{
label: 'Jira summary',
run: (params, spawnAgent) =>
generateJiraIssueSummaryFromContext(
{ description: 'Trace lighthouse signal' },
params,
contractTarget,
spawnAgent
),
output: '"Trace lighthouse signal"\nextra commentary',
expected: { summary: 'Trace lighthouse signal' }
}
]
type Receipt = { paths: string[]; sizes: number[]; content: string; stdin: string; message: string }
async function withReader<T>(
output: string,
@@ -271,55 +165,6 @@ async function withReader<T>(
}
}
it.each(consumers)(
'preserves $label output and failure classification across stdin/file transport',
async (consumer) => {
const spec = agentSpecs.getCommitMessageAgentSpec('omp')
if (!spec) {
throw new Error('Missing OMP spec')
}
for (const fail of [false, true]) {
const delivered = await withReader(consumer.output, fail, (spawn) =>
consumer.run(contractParams, spawn)
)
expect(delivered.receipt.paths).toHaveLength(1)
expect(delivered.receipt.stdin).toBe('')
expect(delivered.receipt.message.endsWith('recipe-message')).toBe(true)
expect(delivered.receipt.content).toContain('Trace lighthouse signal')
expect(delivered.receipt.content.includes('Saved recipe instruction')).toBe(
consumer.label !== 'Jira summary'
)
if (fail) {
expect(delivered.result).toMatchObject({
success: false,
error: expect.stringContaining('OMP CLI command failed with code 7')
})
} else {
expect(delivered.result).toMatchObject({
success: true,
agentLabel: 'OMP',
...consumer.expected
})
}
const legacy = vi.spyOn(agentSpecs, 'getCommitMessageAgentSpec').mockReturnValue({
...spec,
promptDelivery: 'stdin',
buildArgs: (params) => spec.buildArgs(params).slice(0, -1)
})
try {
const previous = await withReader(consumer.output, fail, (spawn) =>
consumer.run(contractParams, spawn)
)
expect(previous.receipt.paths).toHaveLength(0)
expect(previous.receipt.content).toBe(delivered.receipt.content)
expect(previous.result).toEqual(delivered.result)
} finally {
legacy.mockRestore()
}
}
}
)
it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'internal magic'] as const)(
'delivers complete text recipe content: %s',
async (boundary) => {
@@ -363,76 +208,3 @@ it.each(['below', 'at', 'above', 'multibyte', 'BOM run', 'GIF', 'RIFF', 'interna
}
}
)
it.each(['success', 'spawn failure', 'permanent failure'] as const)(
'settles independently of bounded async cleanup after %s',
async (outcome) => {
const originalPlatform = process.platform
const rmMock = vi.mocked(rm)
const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
const locked = Object.assign(new Error('EPERM: prompt handle held'), { code: 'EPERM' })
let directory = ''
Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' })
rmMock.mockClear()
rmMock.mockImplementationOnce(async () => {
throw locked
})
if (outcome === 'permanent failure') {
rmMock.mockRejectedValue(locked)
}
try {
const planned = planCommitMessageGeneration(
{ agentId: 'omp', model: 'default' },
recordedPrompt
)
if (!planned.ok) {
throw new Error(planned.error)
}
const child = createMockDiscoveryChild()
const execution = runLocalSourceControlPlan({
plan: planned.plan,
cwd: '/omp-cleanup',
env: undefined,
operation: 'conversation-name',
spawnAgent: ({ args }) => {
directory = dirname(args[planned.plan.promptFile?.argIndex ?? -1].slice(1))
if (outcome === 'spawn failure') {
throw new Error('Fixture spawn failure')
}
return child
}
})
if (outcome !== 'spawn failure') {
child.stdout.emit('data', Buffer.from('Lighthouse Signal Trace'))
child.emit('close', 0)
}
expect((await execution.result).success).toBe(outcome !== 'spawn failure')
await execution.processClosed
expect(rmMock).toHaveBeenCalledTimes(1)
expect(existsSync(directory)).toBe(true)
if (outcome === 'permanent failure') {
await vi.waitFor(
() =>
expect(errors).toHaveBeenCalledWith(
'[commit-message] Failed to remove generation prompt:',
locked
),
{ timeout: 5000 }
)
expect(rmMock).toHaveBeenCalledTimes(5)
expect(errors).toHaveBeenCalledTimes(1)
expect(existsSync(directory)).toBe(true)
} else {
await vi.waitFor(() => expect(existsSync(directory)).toBe(false), { timeout: 2000 })
expect(rmMock).toHaveBeenCalledTimes(2)
}
} finally {
Object.defineProperty(process, 'platform', { configurable: true, value: originalPlatform })
rmMock.mockImplementation(actualFs.rm)
if (directory) {
await actualFs.rm(directory, { recursive: true, force: true })
}
errors.mockRestore()
}
}
)
@@ -334,75 +334,6 @@ it.each([
}
)
it.each(['success', 'nonzero', 'empty', 'storage', 'pipe-close'] as const)(
'runs the production attempt through real private shell preparation and %s',
async (outcome) => {
let directory = ''
let actualPipeError = false
const execution = withPlatform('win32', () =>
runLocalSourceControlPlan({
plan: plan(tricky.repeat(40)),
cwd,
env: undefined,
operation: 'conversation-name',
spawnAgent: (input) => {
const preparation = input.preparation
if (!preparation) {
throw new Error('Missing preparation')
}
directory = `/tmp/orca-generation-${preparation.args[0]}`
const argv =
outcome === 'pipe-close'
? [
'-c',
`exec 0<&-; printf 'ORCA_GENERATION_READY:%s\\n' "$1" >&2; sleep 0.1`,
'fixture',
preparation.args[0]
]
: [
'-c',
preparation.script,
'fixture',
...preparation.args,
'/bin/sh',
'-c',
outcome === 'empty'
? ':'
: `printf '%s' 'Useful name'; exit ${outcome === 'nonzero' ? 7 : 0}`
]
const child = withPlatform('darwin', () =>
spawnProcess({ program: '/bin/sh', args: argv, stdio: 'pipe' })
)
child.stdin.on('error', (error) => {
actualPipeError ||= 'code' in error && error.code === 'EPIPE'
})
if (outcome === 'storage') {
child.stderr.once('data', () => mkdirSync(join(directory, 'prompt-1.txt')))
}
return child
}
})
)
try {
const result = await execution.result
await execution.processClosed
expect(result.success).toBe(outcome === 'success')
expect(removeTreeMock).toHaveBeenCalledTimes(1)
if (outcome === 'pipe-close') {
expect(actualPipeError).toBe(true)
}
if (outcome === 'success') {
const file = readFileSync(join(directory, 'prompt-1.txt'))
expect(new TextDecoder().decode(file)).toBe(Buffer.from(tricky.repeat(40)).toString())
}
} finally {
if (directory) {
await rm(directory, { recursive: true, force: true })
}
}
}
)
it('delivers a plain UTF-8 policy module and preserves the stdin task after guest materialization', async () => {
const guest = prepareWslPrompt(
{
@@ -1,43 +1,7 @@
import { realKimiOccupiedOutput } from '../../../shared/__fixtures__/kimi-generation-source-shaped'
import { describe, expect, it } from 'vitest'
import { generateBranchNameFromContext } from '../commit-message-text-generation'
describe('generateBranchNameFromContext', () => {
it.each(['pi', 'kimi'] as const)('%s failure diagnostics', async (agentId) => {
const result = await generateBranchNameFromContext(
{ firstPrompt: 'Fix login flow' },
{
agentId,
model: agentId === 'kimi' ? 'default' : 'github-copilot/gpt-5.5'
},
{
kind: 'remote',
cwd: '/repo',
missingBinaryLocation: 'remote PATH',
execute: async () => ({
stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial',
stderr: 'No API key found for github-copilot.',
exitCode: agentId === 'kimi' ? 4 : 1,
timedOut: false
})
}
)
expect(result.success).toBe(false)
if (result.success) {
throw new Error('expected a failure result')
}
if (agentId === 'kimi') {
expect(result.error).toMatch(/Kimi.*active.*Stop.*exit.*try again/)
}
expect(result.failureOutput).toEqual({
label: agentId === 'kimi' ? 'Kimi' : 'Pi',
exitCode: agentId === 'kimi' ? 4 : 1,
stdout: agentId === 'kimi' ? realKimiOccupiedOutput : 'partial',
stderr: 'No API key found for github-copilot.'
})
})
it('reruns Copilot once on its default model when the plan hides the saved model', async () => {
const calls: string[][] = []
const result = await generateBranchNameFromContext(
@@ -1,10 +1,5 @@
import { realKimiOccupiedOutput } from '../../../shared/__fixtures__/kimi-generation-source-shaped'
import { describe, expect, it, vi } from 'vitest'
import { createMockDiscoveryChild } from '../execution/commit-message-text-generation-test-harness'
import { describe, expect, it } from 'vitest'
import { generateConversationNameFromContext } from '../commit-message-text-generation'
import { cancelLocalGeneration } from '../execution/source-control-generation-lanes'
import { generateConversationName } from './conversation-name-generation-request'
import type { SpawnedSourceControlAgentProcess } from '../source-control-text-generation-types'
describe('generateConversationName', () => {
it.each([
@@ -76,33 +71,4 @@ describe('generateConversationName', () => {
error: 'Generated chat name was empty after sanitization.'
})
})
it.each(['cancel', 'occupied'])('handles a local %s outcome', async (outcome) => {
const child = createMockDiscoveryChild()
const spawnAgent = vi.fn(() => {
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: The test child implements every process member the generation lane reads.
return child as unknown as SpawnedSourceControlAgentProcess
})
const pending = generateConversationName({
context: { firstPrompt: 'Fix login' },
params:
outcome === 'cancel'
? { agentId: 'custom', model: '', customAgentCommand: 'agent' }
: { agentId: 'kimi', model: 'default' },
target: { kind: 'local', cwd: '/repo' },
spawnAgent
})
await vi.waitFor(() => expect(spawnAgent).toHaveBeenCalledOnce())
if (outcome === 'occupied') {
child.stdout.emit('data', Buffer.from(realKimiOccupiedOutput))
child.emit('close', 4)
expect(await pending).toMatchObject({
success: false,
error: expect.stringMatching(/Kimi.*active.*Stop.*exit.*try again/)
})
return
}
cancelLocalGeneration('conversation-name', '/repo')
expect(await pending).toMatchObject({ success: false, canceled: true })
})
})
@@ -32,7 +32,6 @@ import {
readIssueCommandUnlessWslStopped,
writeIssueCommandUnlessWslStopped
} from './issue-command-file'
import { RuntimeRepositoryIssueCommand } from '../runtime/repositories/runtime-repository-issue-command'
const WSL_REPO = '\\\\wsl.localhost\\Ubuntu\\home\\me\\repo'
const HOST_REPO = 'C:\\src\\repo'
@@ -67,24 +66,6 @@ describe('issue command reads for a stopped WSL distro (E9)', () => {
expect(mocks.loadHooks).not.toHaveBeenCalled()
})
it("gates the runtime read a paired client's Settings pane makes, and passes a launch's wake", async () => {
const reader = new RuntimeRepositoryIssueCommand({
resolveRepo: async () => ({
id: 'repo-1',
path: WSL_REPO,
displayName: 'repo',
badgeColor: '#000',
addedAt: 1,
kind: 'git'
}),
getLocalGitArgs: () => []
})
await expect(reader.read('id:repo-1')).resolves.toMatchObject({ status: 'error' })
expect(mocks.loadHooks).not.toHaveBeenCalled()
await reader.read('id:repo-1', { wakeWslDistro: true })
expect(mocks.loadHooks).toHaveBeenCalledWith(WSL_REPO)
})
it("refuses a write the user didn't make, leaving the hidden file and the distro alone", async () => {
await expect(writeIssueCommandUnlessWslStopped(WSL_REPO, 'x', {})).rejects.toThrow(
"WSL distro 'Ubuntu' is not running"
@@ -94,15 +75,6 @@ describe('issue command reads for a stopped WSL distro (E9)', () => {
expect(mocks.rmSync).not.toHaveBeenCalled()
})
it("saves the user's own edit, a user act that may start the distro", async () => {
await writeIssueCommandUnlessWslStopped(WSL_REPO, 'mine', {}, { wakeWslDistro: true })
expect(mocks.writeFileSync).toHaveBeenCalledWith(
expect.stringContaining('issue-command'),
'mine\n',
'utf-8'
)
})
it('refuses a host-path repo whose Git runs in the stopped distro', async () => {
await expect(
writeIssueCommandUnlessWslStopped(HOST_REPO, 'x', () => ({ wslDistro: 'Ubuntu' }))
-62
View File
@@ -179,68 +179,6 @@ export type PreloadApi = {
speech: SpeechApi
}
export type {
ClaudeUsageApi,
CodexUsageApi,
MuseUsageApi,
OpenCodeUsageApi
} from './api/agent-usage-api'
export type { AiVaultApi } from './api/ai-vault-api'
export type { AutomationsApi, ExternalAutomationManagerResult } from './api/automation-api'
export type { AppApi } from './api/app-api'
export type {
BrowserApi,
DetectedBrowserInfo,
DetectedBrowserProfileInfo
} from './api/browser/browser-api'
export type { EmulatorApi } from './api/emulator-api'
export type { ExportApi } from './api/filesystem-api'
export type {
NativeChatApi,
NativeChatAppendedMessages,
NativeChatAppendedPayload,
NativeChatReadSessionResult,
NativeChatSubscribeArgs,
NativeChatSubscriptionFrame
} from './api/native-chat-api'
export type {
PluginAutoUpdateEvent,
PluginHostCustomEditor,
PluginHostNewFile,
PluginHostInstallResult,
PluginHostInstallSource,
PluginHostListEntry,
PluginHostLogLine,
PluginHostPanel,
PluginHostStatus,
PluginMarketplaceHostInstallPreview,
PluginMarketplaceHostListing,
PluginMarketplaceHostSourceState
} from './api/plugin-host-api'
export type {
PreflightApi,
PreflightRuntimeContext,
PreflightStatus,
RefreshAgentsResult
} from './api/preflight-api'
export type {
PtyManagementApi,
PtyManagementDaemonCwdClass,
PtyManagementFolderAccessMismatch,
PtyManagementMacTccAttributionHealth,
PtyManagementSession,
PtyManagementSeveredDaemon,
PtyManagementSeveredDaemonRestartResult
} from './api/pty-management-api'
export type {
DiagnosticsBundlePayload,
DiagnosticsStatusPayload,
DiagnosticsUploadPayload,
MemoryApi,
StatsApi
} from './api/telemetry-api'
declare global {
// oxlint-disable-next-line typescript-eslint/consistent-type-definitions -- declaration merging requires interface
interface Window {
+5 -2
View File
@@ -9,8 +9,11 @@ import {
KEYBOARD_LAYOUT_CHANGED_CHANNEL,
type KeyboardLayoutChangeEvent
} from '../../shared/keyboard-layout-events'
import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring'
import { awaitBeforeUnloadCheckpoint, startupDiagnosticsEnabled } from '../preload-runtime-support'
import { prepareAndInvokeAppRestart } from '../renderer/restart/renderer-restart-wiring'
import {
awaitBeforeUnloadCheckpoint,
startupDiagnosticsEnabled
} from '../renderer/renderer-runtime'
import type { PreloadApi } from '../api-types'
export const appApi = {
+2 -1
View File
@@ -1,6 +1,7 @@
import type { ExecutionHostId } from '../../shared/execution-host'
import { ipcRenderer } from 'electron'
import type { ExternalAutomationManagerResult, PreloadApi } from '../api-types'
import type { ExternalAutomationManagerResult } from './automation-api'
import type { PreloadApi } from '../api-types'
import type { AutomationOwnerRef } from '../../shared/automations/ownership/automation-owner-ref'
import type {
ScopedExternalManagerActionRequest,
@@ -17,7 +17,7 @@ import type {
BrowserPagePromptResult
} from '../../../shared/browser/prompts/browser-page-prompt'
import { readBrowserClientHostIdArgument } from '../../../shared/browser/client-hosting/browser-client-host-id-argument'
import { browserClientPageRendererRequests } from '../../preload-runtime-support'
import { browserClientPageRendererRequests } from '../../renderer/renderer-runtime'
import type { PreloadApi } from '../../api-types'
export const browserGuestRegistrationAndDownloadsApi = {
+2 -2
View File
@@ -1,5 +1,5 @@
import { backendUsageTransport } from '../backend-port-client'
import { createUsageProviderApi } from '../usage-provider-api'
import { backendUsageTransport } from '../usage/backend-port-client'
import { createUsageProviderApi } from '../usage/usage-provider-api'
import type { PreloadApi } from '../api-types'
export const claudeUsageApi = createUsageProviderApi(
+2 -2
View File
@@ -1,5 +1,5 @@
import { backendUsageTransport } from '../backend-port-client'
import { createUsageProviderApi } from '../usage-provider-api'
import { backendUsageTransport } from '../usage/backend-port-client'
import { createUsageProviderApi } from '../usage/usage-provider-api'
import type { PreloadApi } from '../api-types'
export const codexUsageApi = createUsageProviderApi(
+2 -2
View File
@@ -9,8 +9,8 @@ import type {
} from '../../shared/crash-reporting'
import type { RendererHeapStatistics } from '../../shared/renderer-heap-statistics'
import type { RendererProcessMemory } from '../../shared/renderer-process-memory'
import { readRendererHeapStatistics } from '../renderer-heap-statistics-reader'
import { readRendererProcessMemory } from '../renderer-process-memory-reader'
import { readRendererHeapStatistics } from '../renderer/diagnostics/renderer-heap-statistics-reader'
import { readRendererProcessMemory } from '../renderer/diagnostics/renderer-process-memory-reader'
import type { PreloadApi } from '../api-types'
export const crashReportsApi = {
+1 -1
View File
@@ -1,4 +1,4 @@
import { preloadE2EConfig } from '../e2e-config'
import { preloadE2EConfig } from '../renderer/e2e-config'
import type { PreloadApi } from '../api-types'
export const e2eApi = {
@@ -1,6 +1,6 @@
import { ipcRenderer } from 'electron'
import type { GitLabMRInvolvement } from '../shared/gitlab-types'
import type { TaskSourceContext } from '../shared/work-items/task-source-context'
import type { GitLabMRInvolvement } from '../../shared/gitlab-types'
import type { TaskSourceContext } from '../../shared/work-items/task-source-context'
type GitLabRepoSelectorArgs = {
repoPath: string
-4
View File
@@ -1,4 +0,0 @@
import { glApi } from '../gitlab'
import type { PreloadApi } from '../api-types'
export const glApiBridge = glApi satisfies PreloadApi['gl']
+2 -2
View File
@@ -1,5 +1,5 @@
import { backendUsageTransport } from '../backend-port-client'
import { createUsageProviderApi } from '../usage-provider-api'
import { backendUsageTransport } from '../usage/backend-port-client'
import { createUsageProviderApi } from '../usage/usage-provider-api'
import type { PreloadApi } from '../api-types'
export const museUsageApi = createUsageProviderApi(
+3 -3
View File
@@ -2,9 +2,9 @@ import { ipcRenderer } from 'electron'
import type {
NativeChatAppendedPayload,
NativeChatReadSessionResult,
NativeChatSubscriptionFrame,
PreloadApi
} from '../api-types'
NativeChatSubscriptionFrame
} from './native-chat-api'
import type { PreloadApi } from '../api-types'
import type { AgentType } from '../../shared/agent-status/contracts/agent-status-types'
import {
NATIVE_CHAT_VISUAL_GUEST_THEME_PUBLISH,
+2 -2
View File
@@ -1,5 +1,5 @@
import { backendUsageTransport } from '../backend-port-client'
import { createUsageProviderApi } from '../usage-provider-api'
import { backendUsageTransport } from '../usage/backend-port-client'
import { createUsageProviderApi } from '../usage/usage-provider-api'
import type { PreloadApi } from '../api-types'
export const openCodeUsageApi = createUsageProviderApi(
+2 -2
View File
@@ -8,8 +8,8 @@ import {
type SwitchOrcaProfileResult,
type TransferOrcaProfileProjectResult
} from '../../shared/orca-profiles'
import { prepareAndInvokeAppRestart } from '../renderer-restart-wiring'
import { awaitBeforeUnloadCheckpoint } from '../preload-runtime-support'
import { prepareAndInvokeAppRestart } from '../renderer/restart/renderer-restart-wiring'
import { awaitBeforeUnloadCheckpoint } from '../renderer/renderer-runtime'
export const orcaProfilesApi = {
list: () => ipcRenderer.invoke('orcaProfiles:list'),
-48
View File
@@ -1,48 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { platformApi } from './platform-bridge'
const mocks = vi.hoisted(() => ({ getLinuxDisplayServer: vi.fn(() => null) }))
vi.mock('../preload-runtime-support', () => ({
getLinuxDisplayServer: mocks.getLinuxDisplayServer
}))
// Electron declares getSystemVersion as required on NodeJS.Process; Node does not have it.
const mutableProcess = process as unknown as { getSystemVersion?: () => string }
async function loadPlatformApi(): Promise<typeof platformApi> {
vi.resetModules()
return (await import('./platform-bridge')).platformApi
}
describe('platformApi.get', () => {
beforeEach(() => {
mocks.getLinuxDisplayServer.mockClear()
})
afterEach(() => {
delete mutableProcess.getSystemVersion
})
it('resolves the immutable payload once and returns the identical object', async () => {
const platformApi = await loadPlatformApi()
const getSystemVersion = vi.fn(() => '25.3.0')
mutableProcess.getSystemVersion = getSystemVersion
const first = platformApi.get()
expect(platformApi.get()).toBe(first)
expect(Object.isFrozen(first)).toBe(true)
expect(getSystemVersion).toHaveBeenCalledTimes(1)
expect(mocks.getLinuxDisplayServer).toHaveBeenCalledTimes(1)
expect(first.platform).toBe(process.platform)
expect(first.arch).toBe(process.arch)
expect(first.osRelease).toBe('25.3.0')
})
it('resolves nothing before the first get, keeping preload startup free', async () => {
await loadPlatformApi()
expect(mocks.getLinuxDisplayServer).not.toHaveBeenCalled()
})
})
+1 -1
View File
@@ -1,4 +1,4 @@
import { getLinuxDisplayServer } from '../preload-runtime-support'
import { getLinuxDisplayServer } from '../renderer/renderer-runtime'
import { parseWindowMaterialArgument } from '../../shared/window-material'
import type { PreloadApi } from '../api-types'
+4 -4
View File
@@ -20,10 +20,10 @@ import type {
PluginAutoUpdateEvent,
PluginHostInstallResult,
PluginHostInstallSource,
PluginHostListEntry,
PluginHostLogLine,
PreloadApi
} from '../api-types'
PluginHostLogLine
} from './plugin-host-api'
import type { PluginHostListEntry } from '../../shared/plugins/plugin-list-entry'
import type { PreloadApi } from '../api-types'
export const pluginsApi = {
list: (): Promise<PluginHostListEntry[]> => ipcRenderer.invoke('plugins:list'),
+2 -1
View File
@@ -1,5 +1,6 @@
import { ipcRenderer } from 'electron'
import type { PreflightRuntimeContext, PreloadApi, RefreshAgentsResult } from '../api-types'
import type { PreflightRuntimeContext, RefreshAgentsResult } from './preflight-api'
import type { PreloadApi } from '../api-types'
import type { ZCodeInteractiveCapability } from '../../shared/zcode-missing-tui'
export const preflightApi = {
+1 -1
View File
@@ -8,7 +8,7 @@ import type {
} from '../../shared/runtime-types'
import type { RuntimeTerminalDriverState } from '../../shared/runtime-session-contracts'
import type { RuntimeRpcResponse } from '../../shared/runtime-rpc-envelope'
import type { RuntimeEnvironmentSubscriptionHandle } from '../runtime-environment-subscriptions'
import type { RuntimeEnvironmentSubscriptionHandle } from '../runtime/runtime-environment-subscriptions'
import type { PreloadApi } from '../api-types'
export const runtimeApi = {
@@ -22,7 +22,7 @@ import {
subscribeCrewAttemptFromPreload,
cancelRuntimeEnvironmentSubscriptionFromPreload,
type RuntimeEnvironmentSubscriptionHandle
} from '../runtime-environment-subscriptions'
} from '../runtime/runtime-environment-subscriptions'
import type { PreloadApi } from '../api-types'
import { managedOrcadApi } from './managed-orcad-api'
import { getWslHostsApi } from './wsl-hosts-api'
@@ -1,11 +1,11 @@
import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest'
import type { PreloadApi } from './api-types'
import type { SshConnectionState, SshProviderEpoch } from '../shared/ssh-types'
import type { PreloadApi } from '../api-types'
import type { SshConnectionState, SshProviderEpoch } from '../../shared/ssh-types'
import type {
HostQualifiedDetectedWorktreeResult,
ListDetectedWorktreesArgs
} from '../shared/detected-worktree-provider-contract'
import type { DetectedWorktreeListResult } from '../shared/worktree/types'
} from '../../shared/detected-worktree-provider-contract'
import type { DetectedWorktreeListResult } from '../../shared/worktree/types'
function listDetectedVariableTypeProbe(api: PreloadApi, args: ListDetectedWorktreesArgs) {
return api.worktrees.listDetected(args)
@@ -66,30 +66,6 @@ describe('native preload SSH authority forwarding', () => {
>()
})
it('forwards host-qualified metadata-only worktree reads', async () => {
await import('./index')
const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
const args = { repoId: 'repo-1', executionHostId: 'ssh:ssh-1' as const }
await api.worktrees.listKnownForExecutionHost?.(args)
expect(invoke).toHaveBeenCalledWith('worktrees:listKnownForExecutionHost', args)
})
it('forwards metadata retirement for authoritatively removed worktrees', async () => {
await import('./index')
const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
const args = {
repoId: 'repo-1',
executionHostId: 'ssh:ssh-1' as const,
worktreeIds: ['repo-1::/remote/deleted']
}
await api.worktrees.forgetRemovedForExecutionHost?.(args)
expect(invoke).toHaveBeenCalledWith('worktrees:forgetRemovedForExecutionHost', args)
})
it('forwards full-pair get and push states without cloning away authority', async () => {
const state: SshConnectionState = {
targetId: 'ssh-1',
@@ -100,7 +76,7 @@ describe('native preload SSH authority forwarding', () => {
connectionGeneration: 29
}
invoke.mockResolvedValueOnce(state)
await import('./index')
await import('../index')
const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
await expect(api.ssh.getState({ targetId: 'ssh-1' })).resolves.toEqual(state)
@@ -126,7 +102,7 @@ describe('native preload SSH authority forwarding', () => {
providerEpoch: 'partial-provider-epoch'
} as SshConnectionState
invoke.mockResolvedValueOnce(partialState)
await import('./index')
await import('../index')
const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
const returned = await api.ssh.getState({ targetId: 'ssh-1' })
@@ -156,7 +132,7 @@ describe('native preload SSH authority forwarding', () => {
})
it('drops malformed full authority before it reaches the renderer', async () => {
await import('./index')
await import('../index')
const api = exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
const onStateChanged = vi.fn()
api.ssh.onStateChanged(onStateChanged)
@@ -1,5 +1,5 @@
import { ipcRenderer } from 'electron'
import { admitCloseActiveTabPayload } from '../close-active-tab-payload-admission'
import { admitCloseActiveTabPayload } from '../renderer/window-commands/close-active-tab-payload-admission'
import type { CloseActiveTabPayload } from '../api/ui-command-event-api'
import type {
BrowserHistoryNavigateCommand,
@@ -11,7 +11,7 @@ import type {
WorktreeDefaultTabsLaunch,
WorktreeSetupLaunch
} from '../../shared/worktree/launch-types'
import { browserFindSubscriptions } from '../preload-runtime-support'
import { browserFindSubscriptions } from '../renderer/renderer-runtime'
import type { PreloadApi } from '../api-types'
export const uiTabAndBrowserCommandsApi = {
+2 -2
View File
@@ -1,7 +1,7 @@
import { ipcRenderer } from 'electron'
import type { UpdateStatus } from '../../shared/update-status-types'
import { prepareAndInvokeUpdaterInstall } from '../renderer-restart-wiring'
import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../preload-runtime-support'
import { prepareAndInvokeUpdaterInstall } from '../renderer/restart/renderer-restart-wiring'
import { awaitBeforeUnloadCheckpoint, updaterQuitAbortRelay } from '../renderer/renderer-runtime'
import type { PreloadApi } from '../api-types'
export const updaterApi = {
@@ -1,239 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { PreloadApi } from './api-types'
import {
ORCA_APP_RESTART_ABORTED_EVENT,
ORCA_APP_RESTART_STARTED_EVENT
} from '../shared/updater-renderer-events'
import { KEYBOARD_LAYOUT_CHANGED_CHANNEL } from '../shared/keyboard-layout-events'
const { exposeInMainWorld, invoke, on, removeListener, send, sendSync, getPathForFile } =
vi.hoisted(() => ({
exposeInMainWorld: vi.fn(),
invoke: vi.fn(),
on: vi.fn(),
removeListener: vi.fn(),
send: vi.fn(),
sendSync: vi.fn(),
getPathForFile: vi.fn(() => '/files/notes.txt')
}))
vi.mock('electron', () => ({
contextBridge: { exposeInMainWorld },
ipcRenderer: { invoke, on, removeListener, send, sendSync },
webFrame: {
getZoomFactor: vi.fn(() => 1),
setZoomFactor: vi.fn(),
setVisualZoomLevelLimits: vi.fn()
},
webUtils: { getPathForFile }
}))
describe('native preload destructive app actions', () => {
const originalContextIsolated = Object.getOwnPropertyDescriptor(process, 'contextIsolated')
let eventTarget: EventTarget
beforeEach(() => {
vi.resetModules()
exposeInMainWorld.mockReset()
invoke.mockReset()
on.mockReset()
removeListener.mockReset()
send.mockReset()
sendSync.mockReset()
Object.defineProperty(process, 'contextIsolated', { configurable: true, value: true })
eventTarget = new EventTarget()
vi.stubGlobal('window', eventTarget)
vi.stubGlobal('document', { addEventListener: vi.fn() })
})
afterEach(() => {
vi.unstubAllGlobals()
if (originalContextIsolated) {
Object.defineProperty(process, 'contextIsolated', originalContextIsolated)
} else {
Reflect.deleteProperty(process, 'contextIsolated')
}
})
const loadApi = async (): Promise<PreloadApi> => {
await import('./index')
return exposeInMainWorld.mock.calls.find(([name]) => name === 'api')?.[1] as PreloadApi
}
it('exposes synchronous file path resolution and a window-local preparation invoke', async () => {
const api = await loadApi()
const file = new File(['x'], 'notes.txt')
expect(api).not.toHaveProperty('getPathForFile')
expect(api.fs.getPathForFile?.(file)).toBe('/files/notes.txt')
expect(getPathForFile).toHaveBeenCalledWith(file)
const request = { paths: ['/files/notes.txt'], consumer: 'agent' as const }
invoke.mockResolvedValue({ paths: request.paths, failures: [] })
await expect(api.fs.prepareDroppedPaths(request)).resolves.toEqual({
paths: request.paths,
failures: []
})
expect(invoke).toHaveBeenCalledExactlyOnceWith('fs:prepareDroppedPaths', request)
})
for (const action of ['reload', 'relaunch'] as const) {
it(`prepares and awaits durability before ${action}`, async () => {
const api = await loadApi()
const calls: string[] = []
eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, () => calls.push('prepared'))
invoke.mockImplementation(async (channel: string) => {
calls.push(channel)
return channel === 'app:await-before-unload-checkpoint' ? { ok: true } : undefined
})
await api.app[action]()
expect(calls).toEqual(['prepared', 'app:await-before-unload-checkpoint', `app:${action}`])
})
it(`refuses ${action} when the durable checkpoint fails`, async () => {
const api = await loadApi()
const aborted = vi.fn()
eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted)
invoke.mockImplementation(async (channel: string) =>
channel === 'app:await-before-unload-checkpoint' ? { ok: false } : undefined
)
await expect(api.app[action]()).rejects.toThrow(
'Failed to persist renderer state before unload.'
)
expect(invoke).not.toHaveBeenCalledWith(`app:${action}`)
expect(aborted).toHaveBeenCalledTimes(1)
})
}
it('exposes the durable checkpoint join the lazy-chunk recovery reload depends on', async () => {
const api = await loadApi()
invoke.mockResolvedValue({ ok: true })
await expect(api.app.awaitBeforeUnloadCheckpoint()).resolves.toBeUndefined()
expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint')
invoke.mockResolvedValue({ ok: false })
await expect(api.app.awaitBeforeUnloadCheckpoint()).rejects.toThrow(
'Failed to persist renderer state before unload.'
)
})
it('preserves both macOS keyboard preload adapters', async () => {
const api = await loadApi()
invoke.mockResolvedValue(undefined)
await api.app.getMacCapturedDigitRowChords()
await api.app.getKeyboardLayoutSnapshot()
const onKeyboardLayoutChanged = vi.fn()
const unsubscribe = api.app.onKeyboardLayoutChanged(onKeyboardLayoutChanged)
const listener = on.mock.calls.find(
([channel]) => channel === KEYBOARD_LAYOUT_CHANGED_CHANNEL
)?.[1] as ((event: unknown, payload: unknown) => void) | undefined
const payload = { phase: 'invalidated', generation: 1 }
listener?.({}, payload)
unsubscribe()
expect(invoke).toHaveBeenCalledWith('app:getMacCapturedDigitRowChords')
expect(invoke).toHaveBeenCalledWith('app:getKeyboardLayoutSnapshot')
expect(onKeyboardLayoutChanged).toHaveBeenCalledExactlyOnceWith(payload)
expect(removeListener).toHaveBeenCalledWith(KEYBOARD_LAYOUT_CHANGED_CHANNEL, listener)
})
it('awaits renderer durability before profile maintenance and preserves its result', async () => {
const api = await loadApi()
const started = vi.fn()
eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started)
let finishCheckpoint = (_result: { ok: boolean }): void => {}
const checkpoint = new Promise((resolve) => {
finishCheckpoint = resolve
})
const result = { status: 'relaunching' }
invoke.mockImplementation((channel: string) =>
channel === 'app:await-before-unload-checkpoint' ? checkpoint : Promise.resolve(result)
)
const switching = api.orcaProfiles.switchProfile({ profileId: 'target' })
await vi.waitFor(() =>
expect(invoke).toHaveBeenCalledWith('app:await-before-unload-checkpoint')
)
expect(started).toHaveBeenCalledOnce()
expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything())
finishCheckpoint({ ok: true })
await expect(switching).resolves.toBe(result)
expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:switch', { profileId: 'target' })
})
it.each(['checkpoint-failed', 'switch-failed', 'already-active'])(
'resets restart preparation when profile switching returns %s',
async (outcome) => {
const api = await loadApi()
const aborted = vi.fn()
eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted)
invoke.mockImplementation(async (channel: string) => {
if (channel === 'app:await-before-unload-checkpoint') {
return { ok: outcome !== 'checkpoint-failed' }
}
if (outcome === 'switch-failed') {
throw new Error('switch failed')
}
return { status: 'already-active' }
})
const switching = api.orcaProfiles.switchProfile({ profileId: 'target' })
await (outcome === 'already-active'
? expect(switching).resolves.toEqual({ status: 'already-active' })
: expect(switching).rejects.toThrow())
expect(aborted).toHaveBeenCalledOnce()
if (outcome === 'checkpoint-failed') {
expect(invoke).not.toHaveBeenCalledWith('orcaProfiles:switch', expect.anything())
}
}
)
it.each(['move', 'copy', 'inactive', 'duplicate', 'recovery'] as const)(
'prepares only a potentially relaunching project transfer: %s',
async (outcome) => {
const api = await loadApi()
const started = vi.fn()
const aborted = vi.fn()
eventTarget.addEventListener(ORCA_APP_RESTART_STARTED_EVENT, started)
eventTarget.addEventListener(ORCA_APP_RESTART_ABORTED_EVENT, aborted)
const args = {
sourceProfileId: outcome === 'inactive' ? 'inactive' : 'active',
targetProfileId: 'target',
repoId: 'repo',
mode: outcome === 'copy' ? ('copy' as const) : ('move' as const)
}
const result =
outcome === 'duplicate'
? { status: 'duplicate-target' }
: { status: 'transferred', willRelaunch: outcome === 'move' }
invoke.mockImplementation(async (channel: string) => {
if (channel === 'orcaProfiles:list') {
return { activeProfileId: 'active' }
}
if (channel === 'app:await-before-unload-checkpoint') {
return { ok: true }
}
if (outcome === 'recovery') {
const listener = on.mock.calls.find(([name]) => name === 'app:restart-committed')?.[1]
expect(listener).toBeTypeOf('function')
listener()
throw new Error('move requires recovery')
}
return result
})
const transfer = api.orcaProfiles.transferProject(args)
await (outcome === 'recovery'
? expect(transfer).rejects.toThrow('move requires recovery')
: expect(transfer).resolves.toBe(result))
const needsPreparation = outcome !== 'copy' && outcome !== 'inactive'
expect(started).toHaveBeenCalledTimes(needsPreparation ? 1 : 0)
expect(aborted).toHaveBeenCalledTimes(outcome === 'duplicate' ? 1 : 0)
expect(invoke).toHaveBeenLastCalledWith('orcaProfiles:transferProject', args)
}
)
})
@@ -1,12 +1,12 @@
import {
createContentScriptRelayBridge,
installContentScriptRelayFilter
} from './browser-extension-content-script-relay'
import { installBrowserExtensionInertApis } from './browser-extension-inert-apis'
} from './browser/extensions/messaging/browser-extension-content-script-relay'
import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis'
import {
installBrowserExtensionStorageSync,
PRELOAD_STORAGE_SYNC_CONSTANTS
} from './browser-extension-storage-sync'
} from './browser/extensions/storage/browser-extension-storage-sync'
/**
* Orca's content script, bundled into one standalone file that Orca's manifest rewrite puts first
@@ -1,159 +0,0 @@
import { runInNewContext } from 'node:vm'
import { describe, expect, it, vi } from 'vitest'
import type { BrowserExtensionInvokeReply } from './browser-extension-main-world'
import {
installBrowserExtensionNativeMessaging,
PRELOAD_NATIVE_MESSAGING_NAMESPACE,
type BrowserExtensionNativeMessagingContext
} from './browser-extension-native-messaging'
type Reply = BrowserExtensionInvokeReply
type Call = { method: string; args: unknown[] }
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object'
}
/** Calls `path` (e.g. 'onMessage.addListener') on `owner` with its parent as `this`. */
function call(owner: unknown, path: string, ...args: unknown[]): unknown {
const keys = path.split('.')
const leaf = keys.pop() ?? ''
const parent = keys.reduce<unknown>(
(value, key) => (isRecord(value) ? value[key] : undefined),
owner
)
const fn = isRecord(parent) ? parent[leaf] : undefined
if (typeof fn !== 'function') {
throw new Error(`${path} is not a function`)
}
return fn.apply(parent, args)
}
/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */
function install(
permissions: Record<string, string[]>,
context: BrowserExtensionNativeMessagingContext = 'page'
) {
const runtime: Record<string, unknown> = { getManifest: () => permissions }
const browserRuntime: Record<string, unknown> = {}
const calls: Call[] = []
const listens: unknown[][] = []
const pending = new Map<string, (reply: Reply) => void>()
let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null
const bridge = {
call: (namespace: string, method: string, args: unknown[]) => {
expect(namespace).toBe(PRELOAD_NATIVE_MESSAGING_NAMESPACE)
calls.push({ method, args })
return new Promise<Reply>((resolve) => pending.set(`${method}:${String(args[0])}`, resolve))
},
listen: (namespace: string, event: string, active: boolean) =>
listens.push([namespace, event, active]),
onEvent: (handler: typeof dispatch) => {
dispatch = handler
},
passesFilter: () => true
}
const error = vi.fn()
const realm = {
chrome: { runtime },
browser: { runtime: browserRuntime },
console: { error },
JSON,
Math,
Date,
Promise
}
runInNewContext(`(${installBrowserExtensionNativeMessaging.toString()})(bridge, context)`, {
...realm,
globalThis: realm,
bridge,
context
})
return {
runtime,
browserRuntime,
calls,
listens,
error,
/** The id the installer chose for the n-th call's port. */
portId: (index = 0) => String(calls[index]?.args[0]),
lastError: () => (isRecord(runtime.lastError) ? runtime.lastError.message : undefined),
reply: (key: string, value: Reply) => pending.get(key)?.(value),
emit: (args: unknown[]) => dispatch?.(PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', args)
}
}
const tick = () => new Promise((resolve) => setTimeout(resolve, 0))
describe('chrome.runtime native messaging in extension contexts', () => {
it('queues posts until the host runs and routes replies by port', async () => {
const page = install({ permissions: ['nativeMessaging'] })
const port = call(page.runtime, 'connectNative', 'com.example.vault')
const received: unknown[][] = []
call(port, 'onMessage.addListener', (message: unknown, from: unknown) =>
received.push([message, from === port])
)
call(port, 'postMessage', { hello: 'é' })
expect(isRecord(port) && port.name).toBe('')
const id = page.portId()
expect(page.calls).toEqual([{ method: 'connect', args: [id, 'com.example.vault'] }])
// A reply can beat the connect answer; it still reaches the port.
page.emit([id, 'message', '{"early":true}'])
page.reply(`connect:${id}`, { ok: true, value: undefined })
await tick()
expect(page.calls[1]).toEqual({ method: 'postMessage', args: [id, '{"hello":"é"}'] })
page.emit(['another-port', 'message', '{"stray":1}'])
expect(received).toEqual([[{ early: true }, true]])
expect(page.listens).toEqual([])
})
it('fires onDisconnect with runtime.lastError set only during the call', async () => {
const page = install({ permissions: ['nativeMessaging'] })
const port = call(page.runtime, 'connectNative', 'com.example.missing')
const seen: unknown[] = []
call(port, 'onDisconnect.addListener', () => seen.push(page.lastError()))
page.reply(`connect:${page.portId()}`, {
ok: false,
error: 'Specified native messaging host not found.'
})
await tick()
expect(seen).toEqual(['Specified native messaging host not found.'])
expect(page.runtime.lastError).toBeUndefined()
expect(() => call(port, 'postMessage', 1)).toThrow(
'Attempting to use a disconnected port object'
)
})
it('lets main release a port the extension dropped while it was starting', async () => {
const worker = install({ permissions: ['nativeMessaging'] }, 'worker')
const port = call(worker.runtime, 'connectNative', 'com.example.vault')
expect(worker.listens).toEqual([[PRELOAD_NATIVE_MESSAGING_NAMESPACE, 'onPortEvent', true]])
call(port, 'disconnect')
worker.reply(`connect:${worker.portId()}`, { ok: true, value: undefined })
await tick()
expect(worker.calls.at(-1)).toEqual({ method: 'disconnect', args: [worker.portId()] })
})
it('answers sendNativeMessage with a promise, or a callback that sees lastError', async () => {
const page = install({ permissions: ['nativeMessaging'] })
const promised = call(page.runtime, 'sendNativeMessage', 'com.example.vault', { q: 1 })
expect(page.calls[0]).toEqual({
method: 'sendNativeMessage',
args: ['com.example.vault', '{"q":1}']
})
page.reply('sendNativeMessage:com.example.vault', { ok: true, value: '{"a":2}' })
await expect(promised).resolves.toEqual({ a: 2 })
const results: unknown[] = []
call(page.runtime, 'sendNativeMessage', 'com.example.gone', 1, (response: unknown) =>
results.push([response, page.lastError()])
)
await tick()
page.reply('sendNativeMessage:com.example.gone', {
ok: false,
error: 'Native host has exited.'
})
await tick()
expect(results).toEqual([[undefined, 'Native host has exited.']])
})
})
+11 -11
View File
@@ -3,30 +3,30 @@ import {
BROWSER_EXTENSION_API_SURFACE,
PRELOAD_BROWSER_EXTENSION_EVENT_CHANNEL,
PRELOAD_BROWSER_EXTENSION_INVOKE_CHANNEL
} from './browser-extension-api-surface'
} from './browser/extensions/api/browser-extension-api-surface'
import {
installBrowserExtensionApis,
type BrowserExtensionInvokeReply,
type BrowserExtensionMainWorldBridge
} from './browser-extension-main-world'
} from './browser/extensions/api/browser-extension-main-world'
import {
installBrowserExtensionDocumentTargets,
PRELOAD_FIRST_DISCARDED_TAB_ID
} from './browser-extension-document-targets'
import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters'
import { installBrowserExtensionInertApis } from './browser-extension-inert-apis'
import { installContentScriptRelayFilter } from './browser-extension-content-script-relay'
import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging'
import { installBrowserExtensionFrameLifetime } from './browser-extension-frame-lifetime'
import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay'
} from './browser/extensions/documents/browser-extension-document-targets'
import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters'
import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis'
import { installContentScriptRelayFilter } from './browser/extensions/messaging/browser-extension-content-script-relay'
import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging'
import { installBrowserExtensionFrameLifetime } from './browser/extensions/api/browser-extension-frame-lifetime'
import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay'
import {
installBrowserExtensionStorageSync,
PRELOAD_STORAGE_SYNC_CONSTANTS
} from './browser-extension-storage-sync'
} from './browser/extensions/storage/browser-extension-storage-sync'
import {
CHROME_WEB_STORE_ORIGIN,
installChromeWebStoreBridge
} from './browser-extension-web-store-bridge'
} from './browser/extensions/web-store/browser-extension-web-store-bridge'
const electron: { contextBridge: ContextBridge; ipcRenderer: IpcRenderer } = require('electron')
const { contextBridge, ipcRenderer } = electron
@@ -1,209 +0,0 @@
import { runInNewContext } from 'node:vm'
import { describe, expect, it, vi } from 'vitest'
import type { BrowserExtensionInvokeReply } from './browser-extension-main-world'
import {
installBrowserExtensionStorageSync,
PRELOAD_STORAGE_SYNC_CONSTANTS,
PRELOAD_STORAGE_SYNC_NAMESPACE
} from './browser-extension-storage-sync'
type Runtime = { lastError?: { message: string } }
function nativeEvent() {
const listeners = new Set<unknown>()
return {
listeners,
addListener: vi.fn((callback: unknown) => listeners.add(callback)),
removeListener: vi.fn((callback: unknown) => listeners.delete(callback))
}
}
/** Runs the installer from its source text, as contextBridge.executeInMainWorld does. */
function install(
reply: (method: string, args: unknown[]) => BrowserExtensionInvokeReply,
forward?: (changes: unknown, from?: string) => void
) {
const runtime: Runtime = {}
const native = nativeEvent()
const nativeSync = { get: vi.fn(), set: vi.fn() }
const chrome = { runtime, storage: { local: {}, sync: nativeSync, onChanged: native } }
let dispatch: ((namespace: string, event: string, args: unknown[]) => void) | null = null
const calls: unknown[][] = []
const listens: unknown[][] = []
const bridge = {
call: async (namespace: string, method: string, args: unknown[]) => {
calls.push([namespace, method, args])
return reply(method, args)
},
listen: (namespace: string, event: string, active: boolean) =>
listens.push([namespace, event, active]),
onEvent: (handler: typeof dispatch) => {
dispatch = handler
},
passesFilter: () => true
}
const realm = { chrome, console, JSON, Promise }
const relay: unknown = runInNewContext(
`(${installBrowserExtensionStorageSync.toString()})(bridge, constants, forward)`,
{
...realm,
globalThis: realm,
bridge,
constants: PRELOAD_STORAGE_SYNC_CONSTANTS,
forward
}
)
return {
relay: (method: string, args: unknown[], from?: string): unknown =>
typeof relay === 'function' ? relay(method, args, from) : undefined,
chrome,
native,
nativeSync,
calls,
listens,
emit: (changes: unknown) => dispatch?.(PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', [changes])
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === 'object'
}
function call(root: unknown, path: string, ...args: unknown[]): unknown {
const keys = path.split('.')
const name = keys.pop() ?? ''
const owner = keys.reduce<unknown>(
(value, key) => (isRecord(value) ? value[key] : undefined),
root
)
const fn = isRecord(owner) ? owner[name] : null
if (typeof fn !== 'function') {
throw new Error(`${path} is not a function`)
}
return fn.call(owner, ...args)
}
describe('installBrowserExtensionStorageSync', () => {
it('replaces the disabled native area with calls to main, as promises or callbacks', async () => {
const page = install((method) =>
method === 'get' ? { ok: true, value: { theme: 'dark' } } : { ok: true, value: undefined }
)
expect(page.chrome.storage.sync).not.toBe(page.nativeSync)
expect(page.chrome.storage.sync).toMatchObject({ QUOTA_BYTES: 102_400, MAX_ITEMS: 512 })
await expect(call(page.chrome, 'storage.sync.get', 'theme')).resolves.toEqual({
theme: 'dark'
})
const got = await new Promise((resolve) => call(page.chrome, 'storage.sync.get', resolve))
expect(got).toEqual({ theme: 'dark' })
const setDone = vi.fn()
expect(
call(page.chrome, 'storage.sync.set', { at: new Date(0), skip: undefined }, setDone)
).toBeUndefined()
await vi.waitFor(() => expect(setDone).toHaveBeenCalledWith())
await expect(
call(page.chrome, 'storage.sync.setAccessLevel', {
accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS'
})
).resolves.toBeUndefined()
await expect(
call(page.chrome, 'storage.sync.setAccessLevel', { accessLevel: 'TRUSTED_CONTEXTS' })
).rejects.toThrow('This StorageArea is not available for setting access level')
expect(page.calls).toEqual([
[PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']],
[PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', []],
[PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ at: '1970-01-01T00:00:00.000Z' }]]
])
expect(page.nativeSync.get).not.toHaveBeenCalled()
expect(page.nativeSync.set).not.toHaveBeenCalled()
})
it('sets lastError only inside a failed callback and rejects a failed promise', async () => {
const page = install(() => ({ ok: false, error: 'QUOTA_BYTES quota exceeded' }))
const lastError = await new Promise((resolve) =>
call(page.chrome, 'storage.sync.set', { big: 1 }, () =>
resolve(page.chrome.runtime.lastError?.message)
)
)
expect(lastError).toBe('QUOTA_BYTES quota exceeded')
expect(page.chrome.runtime.lastError).toBeUndefined()
await expect(call(page.chrome, 'storage.sync.set', { big: 1 })).rejects.toThrow(
'QUOTA_BYTES quota exceeded'
)
})
it("delivers main's sync changes to sync.onChanged and storage.onChanged with 'sync'", async () => {
const own = { mine: { newValue: 1 } }
const page = install((method) => ({ ok: true, value: method === 'set' ? own : undefined }))
const all: unknown[][] = []
const area: unknown[][] = []
const onAll = (changes: unknown, areaName: unknown) => all.push([areaName, changes])
call(page.chrome, 'storage.onChanged.addListener', onAll)
call(page.chrome, 'storage.sync.onChanged.addListener', (changes: unknown) =>
area.push([changes])
)
// The underlying onChanged keeps its own listeners for local and session.
expect(page.native.listeners.has(onAll)).toBe(true)
expect(call(page.chrome, 'storage.onChanged.hasListener', onAll)).toBe(true)
expect(page.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]])
const changes = { theme: { oldValue: 'light', newValue: 'dark' } }
page.emit(changes)
expect(all).toEqual([['sync', changes]])
expect(area).toEqual([[changes]])
// Main skips the writer, which fires its own listeners from the changes main returns.
await expect(call(page.chrome, 'storage.sync.set', { mine: 1 })).resolves.toBeUndefined()
expect(all).toEqual([
['sync', changes],
['sync', own]
])
expect(area).toEqual([[changes], [own]])
call(page.chrome, 'storage.onChanged.removeListener', onAll)
expect(page.native.listeners.has(onAll)).toBe(false)
page.emit(changes)
expect(all).toHaveLength(2)
expect(area).toHaveLength(3)
})
it("makes a content script's relayed call and fires this context's listeners for its writes", async () => {
const changes = { theme: { newValue: 'dark' } }
const worker = install((method) => ({ ok: true, value: method === 'set' ? changes : 'value' }))
const heard: unknown[] = []
call(worker.chrome, 'storage.sync.onChanged.addListener', (change: unknown) =>
heard.push(change)
)
await expect(worker.relay('get', ['theme'])).resolves.toEqual({ ok: true, value: 'value' })
await expect(worker.relay('set', [{ theme: 'dark' }])).resolves.toEqual({
ok: true,
value: changes
})
expect(heard).toEqual([changes])
await expect(worker.relay('setAccessLevel', [{}])).resolves.toMatchObject({ ok: false })
expect(worker.calls).toEqual([
[PRELOAD_STORAGE_SYNC_NAMESPACE, 'get', ['theme']],
[PRELOAD_STORAGE_SYNC_NAMESPACE, 'set', [{ theme: 'dark' }]]
])
})
it('passes every sync change on to content scripts, naming the one that wrote it', async () => {
const own = { mine: { newValue: 1 } }
const forward = vi.fn()
const worker = install(() => ({ ok: true, value: own }), forward)
// Listens with no listener of its own: content scripts hear other contexts only this way.
expect(worker.listens).toEqual([[PRELOAD_STORAGE_SYNC_NAMESPACE, 'onChanged', true]])
const elsewhere = { theme: { newValue: 'dark' } }
worker.emit(elsewhere)
await call(worker.chrome, 'storage.sync.set', { mine: 1 })
await worker.relay('set', [{ mine: 1 }], 'cs-1')
expect(forward.mock.calls).toEqual([
[elsewhere, undefined],
[own, undefined],
[own, 'cs-1']
])
})
})
@@ -1,48 +0,0 @@
// @vitest-environment happy-dom
import { afterEach, describe, expect, it } from 'vitest'
import { adaptChromeWebStoreWordingForOrca } from './browser-extension-web-store-wording'
const flushMutations = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))
afterEach(() => {
document.body.innerHTML = ''
})
describe('adaptChromeWebStoreWordingForOrca', () => {
it('renames the install wording but keeps the store name', () => {
document.body.innerHTML =
'<a>Chrome Web Store</a><button aria-label="Add to Chrome"><span>Add to Chrome</span></button>'
adaptChromeWebStoreWordingForOrca()
expect(document.querySelector('a')?.textContent).toBe('Chrome Web Store')
expect(document.querySelector('button')?.getAttribute('aria-label')).toBe('Add to Orca')
expect(document.querySelector('span')?.textContent).toBe('Add to Orca')
})
it('renames wording the store draws later, including the removal toast', async () => {
adaptChromeWebStoreWordingForOrca()
const button = document.createElement('span')
button.textContent = 'Remove from Chrome'
document.body.appendChild(button)
const toast = document.createElement('div')
toast.textContent = 'Bitwarden has been removed from Chrome.'
document.body.appendChild(toast)
await flushMutations()
expect(button.textContent).toBe('Remove from Orca')
expect(toast.textContent).toBe('Bitwarden has been removed from Orca.')
button.firstChild!.nodeValue = 'Add to Chrome'
await flushMutations()
expect(button.textContent).toBe('Add to Orca')
})
it('hides the switch-to-Chrome banner and shows the box again when the store reuses it', async () => {
document.body.innerHTML =
'<section><div id="banner"><div><div>Switch to Chrome to install extensions and themes</div></div><a>Install Chrome</a></div><h1>Vault</h1></section>'
adaptChromeWebStoreWordingForOrca()
const banner = document.getElementById('banner')!
expect(banner.style.display).toBe('none')
expect(document.querySelector('h1')?.textContent).toBe('Vault')
banner.innerHTML = '<div>This item is disabled</div><a>Enable now</a>'
await flushMutations()
expect(banner.style.display).toBe('')
})
})
+9 -9
View File
@@ -5,28 +5,28 @@ import {
decodeBrowserExtensionWireJson,
encodeBrowserExtensionWireJson
} from '../shared/browser/extensions/browser-extension-worker-api'
import { BROWSER_EXTENSION_API_SURFACE } from './browser-extension-api-surface'
import { BROWSER_EXTENSION_API_SURFACE } from './browser/extensions/api/browser-extension-api-surface'
import {
createContentScriptSyncForward,
installContentScriptRelayFilter
} from './browser-extension-content-script-relay'
} from './browser/extensions/messaging/browser-extension-content-script-relay'
import {
installBrowserExtensionDocumentTargets,
PRELOAD_FIRST_DISCARDED_TAB_ID
} from './browser-extension-document-targets'
import { passesBrowserExtensionEventFilter } from './browser-extension-event-filters'
import { installBrowserExtensionInertApis } from './browser-extension-inert-apis'
} from './browser/extensions/documents/browser-extension-document-targets'
import { passesBrowserExtensionEventFilter } from './browser/extensions/api/browser-extension-event-filters'
import { installBrowserExtensionInertApis } from './browser/extensions/api/browser-extension-inert-apis'
import {
installBrowserExtensionApis,
type BrowserExtensionInvokeReply,
type BrowserExtensionMainWorldBridge
} from './browser-extension-main-world'
import { installBrowserExtensionNativeMessaging } from './browser-extension-native-messaging'
import { installBrowserExtensionStorageRelay } from './browser-extension-storage-relay'
} from './browser/extensions/api/browser-extension-main-world'
import { installBrowserExtensionNativeMessaging } from './browser/extensions/messaging/browser-extension-native-messaging'
import { installBrowserExtensionStorageRelay } from './browser/extensions/storage/browser-extension-storage-relay'
import {
installBrowserExtensionStorageSync,
PRELOAD_STORAGE_SYNC_CONSTANTS
} from './browser-extension-storage-sync'
} from './browser/extensions/storage/browser-extension-storage-sync'
/**
* Orca's API shim for extension service workers, bundled into one standalone script that Orca's
+4 -4
View File
@@ -1,11 +1,11 @@
import type { ContextBridge, IpcRenderer, WebFrame } from 'electron'
import { installBrowserPasswordDetector } from './browser-password-detector'
import { installBrowserPasswordDetector } from './browser/passwords/browser-password-detector'
import {
installBrowserWindowCloseGuard,
PRELOAD_BROWSER_GUEST_WINDOW_CLOSE_CHANNEL
} from './browser-window-close-installation'
import { installBrowserWindowPrompt } from './browser-window-prompt-installation'
import { installNativeChatVisualGuestTheme } from './native-chat-visual-guest-theme'
} from './browser/window-controls/browser-window-close-installation'
import { installBrowserWindowPrompt } from './browser/window-controls/browser-window-prompt-installation'
import { installNativeChatVisualGuestTheme } from './native-chat/native-chat-visual-guest-theme'
// Raw require keeps the sandboxed preload standalone in the CJS build.
const electron: {
+1 -1
View File
@@ -3,7 +3,7 @@ import {
BROWSER_PASSKEY_REQUEST_CANCEL_CHANNEL,
BROWSER_PASSKEY_REQUEST_PENDING_CHANNEL
} from '../shared/browser-passkey-request'
import { installBrowserPasskeyRequestWatch } from './browser-passkey-request-watch'
import { installBrowserPasskeyRequestWatch } from './browser/passkeys/browser-passkey-request-watch'
// A session preload: it runs in every frame of every browser page, popup and serve window.
const electron: {
@@ -1,62 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { buildSync } from 'esbuild'
import { fileURLToPath } from 'node:url'
import { runInNewContext } from 'node:vm'
import { installBrowserWindowCloseGuard } from './browser-window-close-installation'
import { BROWSER_GUEST_WINDOW_CLOSE_CHANNEL } from '../shared/browser-guest-window-close'
describe('browser window close guard', () => {
afterEach(() => {
vi.unstubAllGlobals()
})
it('replaces the native close with a non-replaceable request to Orca', () => {
const nativeClose = vi.fn()
const requestClose = vi.fn()
vi.stubGlobal('window', { close: nativeClose })
installBrowserWindowCloseGuard(requestClose)
expect(window.close()).toBeUndefined()
expect(nativeClose).not.toHaveBeenCalled()
expect(requestClose).toHaveBeenCalledTimes(1)
expect(Reflect.set(window, 'close', nativeClose)).toBe(false)
})
it.each([true, false])('routes a close only from the top frame: %s', (isMainFrame) => {
const sendToHost = vi.fn()
const nativeClose = vi.fn()
const pageWindow = { close: nativeClose }
const preload = buildSync({
entryPoints: [fileURLToPath(new URL('./browser-guest.ts', import.meta.url))],
bundle: true,
platform: 'node',
format: 'cjs',
external: ['electron'],
write: false
}).outputFiles[0].text
runInNewContext(preload, {
window: pageWindow,
process: { isMainFrame },
require: (name: string) => {
expect(name).toBe('electron')
return {
ipcRenderer: { sendToHost },
contextBridge: {
executeInMainWorld: (script: {
func: (requestClose: () => void) => void
args: [() => void]
}) => script.func(...script.args)
}
}
}
})
pageWindow.close()
expect(nativeClose).toHaveBeenCalledTimes(isMainFrame ? 0 : 1)
expect(sendToHost.mock.calls).toEqual(isMainFrame ? [[BROWSER_GUEST_WINDOW_CLOSE_CHANNEL]] : [])
})
})

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