refactor(shared): organize file operations and storage owners (#39746)

This commit is contained in:
Neil
2026-11-07 22:58:35 -08:00
committed by GitHub
parent 82c3c05a70
commit 83f8e6340d
815 changed files with 1908 additions and 16685 deletions
@@ -4,10 +4,10 @@ on:
types: [opened, synchronize, reopened, ready_for_review, converted_to_draft]
paths:
- 'src/main/zcode/**'
- 'src/shared/node-bounded-file-reader*'
- 'src/shared/file-content/node-bounded-file-reader*'
- 'src/main/rate-limits/**'
- 'src/shared/secure-file*'
- 'src/shared/secure-path-windows-acl*'
- 'src/shared/secure-storage/secure-file*'
- 'src/shared/secure-storage/secure-path-windows-acl*'
- 'src/shared/windows-security-descriptor*'
- '.github/workflows/zcode-account-contract.yml'
- '.github/workflows/zcode-credential-contract.yml'
@@ -62,14 +62,14 @@ jobs:
fi
if [ "$diff_status" = 1 ]; then
if git diff --quiet --no-renames HEAD^1 HEAD -- \
src/main/zcode/ ':(glob)src/shared/node-bounded-file-reader*' src/main/rate-limits/ \
src/main/zcode/ ':(glob)src/shared/file-content/node-bounded-file-reader*' src/main/rate-limits/ \
.github/workflows/zcode-account-contract.yml \
.github/workflows/zcode-credential-contract.yml \
config/scripts/ci/workflow-contracts/zcode-credential-workflow.test.mjs; then
account=false
fi
if git diff --quiet --no-renames HEAD^1 HEAD -- \
src/main/zcode/ ':(glob)src/shared/secure-file*' ':(glob)src/shared/secure-path-windows-acl*' \
src/main/zcode/ ':(glob)src/shared/secure-storage/secure-file*' ':(glob)src/shared/secure-storage/secure-path-windows-acl*' \
':(glob)src/shared/windows-security-descriptor*' \
.github/workflows/zcode-credential-contract.yml \
config/scripts/ci/workflow-contracts/zcode-credential-workflow.test.mjs; then
@@ -90,7 +90,7 @@ jobs:
no-cache: true
- name: Verify read-only credentials and account changes
if: ${{ !cancelled() && steps.scope.outputs.account == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }}
run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service-zcode-usage.test.ts src/shared/node-bounded-file-reader-sync.test.ts
- name: Verify rollback and native Windows permissions
run: pnpm test src/main/zcode/zcode-v2-plan-credentials.test.ts src/main/zcode/zcode-v2-personal-overlay-raw-json.test.ts src/main/rate-limits/service-zcode-usage.test.ts src/shared/file-content/node-bounded-file-reader-sync.test.ts
- name: Verify rollback and secure storage
if: ${{ !cancelled() && steps.scope.outputs.credentials == 'true' && steps.dependencies.outcome == 'success' && steps.bun.outcome == 'success' }}
run: pnpm test src/main/zcode/zcode-plan-api-key-store.test.ts src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts src/main/zcode/zcode-plan-api-key-store-publication-race.test.ts src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts src/shared/secure-file.test.ts
run: pnpm test src/main/zcode/zcode-plan-api-key-store.test.ts src/main/zcode/zcode-plan-api-key-store-plaintext-rollback.test.ts src/shared/secure-storage/secure-file.test.ts
-3
View File
@@ -309,7 +309,6 @@
1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts
1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/viewport/terminal-fit-restore.test.ts
1 test-no-real-time-wait:src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts
2 test-no-real-time-wait:src/renderer/src/lib/execute-open-editor-path-move.test.ts
1 test-no-real-time-wait:src/renderer/src/lib/agent-session/resume/cli-fork/native-chat-cli-fork-preparation.test.ts
1 test-no-real-time-wait:src/renderer/src/lib/orca-yaml-trust-prompt-slot-eviction.test.ts
2 test-no-real-time-wait:src/renderer/src/store/slices/workspace-cleanup/workspace-cleanup-removal-preflight.test.ts
@@ -321,7 +320,6 @@
1 test-no-real-time-wait:src/shared/git/status/git-branch-line-total-soft-deadline.test.ts
2 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-auth-refusal.test.ts
1 test-no-real-time-wait:src/shared/remote-runtime/control/remote-runtime-shared-control-standing-intent.test.ts
1 test-no-real-time-wait:src/shared/secure-path-windows-acl.win32.test.ts
1 test-no-real-time-wait:src/shared/setup-agent-sequencing-codex-no-daemon.test.ts
2 test-no-real-time-wait:src/shared/setup-agent-sequencing.test.ts
2 test-no-real-time-wait:src/shared/startup-command-staging.node-pty.test.ts
@@ -964,7 +962,6 @@
1 test-timeout-needs-reason:tests/e2e/paired-mobile-serve-restart-terminal-tabs.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-pane-title-desktop-host.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-preview-address-bar-convergence.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-quick-open-large-tree.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-browser-ghost-subscriber-rejoin.spec.ts
1 test-timeout-needs-reason:tests/e2e/paired-remote-browser-link-open-routing.spec.ts
2 test-timeout-needs-reason:tests/e2e/paired-remote-browser-stream-reconnect.spec.ts
+1 -1
View File
@@ -45,4 +45,4 @@
2 src/main/pty/shell-startup/zsh-startup-hook-pty-harness.ts
1 src/shared/fish-binary-requirement.ts
1 src/shared/openssh-default-shell.ts
1 src/shared/secure-file.ts
1 src/shared/secure-storage/secure-file.ts
File diff suppressed because one or more lines are too long
@@ -73,14 +73,6 @@
"reason": "Reviewed data/URL parsing only; no indirect repository input. Imported source dependencies remain graph edges.",
"contextSha256": "747ec5af67a0b60890da900a83fa255d3b96e2fa17d9199f8e483ef5051b213c"
},
{
"file": "src/shared/doc-preview-scheme.ts",
"inputs": [],
"emptyEnv": [],
"reason": "Reviewed URL/data projection only; no indirect repository reads. The entire local source closure and dependency/runtime context are fingerprinted.",
"contextSha256": "747ec5af67a0b60890da900a83fa255d3b96e2fa17d9199f8e483ef5051b213c",
"sourceClosureSha256": "4a3a0dab2fc5b009d4e4e0d6bb5ba49dae08726f3d94fa83c54283f21f8df097"
},
{
"file": "src/shared/node-dist-mirror.ts",
"inputs": [],
@@ -3,7 +3,7 @@ import { performance } from 'node:perf_hooks'
import { build } from 'esbuild'
const bundled = await build({
entryPoints: ['src/shared/quick-open-filter.ts'],
entryPoints: ['src/shared/quick-open/quick-open-filter.ts'],
bundle: true,
platform: 'node',
format: 'esm',
@@ -1,8 +1,9 @@
import { mkdtempSync, mkdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { mkdtempSync, mkdirSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import process from 'node:process'
import { copyScriptWithLocalModules } from '../../test-fixtures/script-copy-closure/script-module-dependencies.mjs'
const BASELINE_COMMIT = 'bf0c77d5bc800e19117084c27fd1441eda9134ad'
const AFFECTED_MAIN_COMMIT = '25abb9368d98ad84a174f530e02f4228d2269062'
@@ -17,7 +18,7 @@ try {
const baselineRoot = extractSource(BASELINE_COMMIT, 'baseline')
const affectedRoot = extractSource(AFFECTED_MAIN_COMMIT, 'affected-main')
const revertedRoot = extractSource('HEAD', 'candidate-reverted')
restoreAffectedStoreFiles(revertedRoot)
restoreAffectedStoreFiles(revertedRoot, affectedRoot)
const baselineData = makeDataDir('baseline-data')
runOracle('baseline write', baselineRoot, 'write-legacy', baselineData)
@@ -70,15 +71,12 @@ function extractSource(commit, name) {
return destination
}
function restoreAffectedStoreFiles(destination) {
for (const relativePath of [
'src/shared/ephemeral-vm-runtime-store.ts',
'src/shared/ephemeral-vm-runtimes.ts'
]) {
const result = run('git', ['show', `${AFFECTED_MAIN_COMMIT}:${relativePath}`], {
encoding: 'utf8'
})
writeFileSync(join(destination, relativePath), result.stdout)
function restoreAffectedStoreFiles(destination, affectedRoot) {
for (const name of ['ephemeral-vm-runtime-store.ts', 'ephemeral-vm-runtimes.ts']) {
copyScriptWithLocalModules(
join(affectedRoot, 'src/shared', name),
join(destination, 'src/shared')
)
}
}
@@ -25,7 +25,7 @@ const GATED_FAMILIES = [
},
{ modules: ['@orca/process-host'], advice: { runProcessSync: PROCESS_ADVICE } },
{
modules: ['src/shared/secure-path-windows-acl'],
modules: ['src/shared/secure-storage/secure-path-windows-acl'],
advice: { restrictWindowsPathSync: SECURE_ADVICE }
},
{
@@ -71,7 +71,7 @@ describe('main sync-spawn ratchet', () => {
['getWslHome', 'listWslDistros']
],
[
"import * as acl from '..\\\\shared\\\\secure-path-windows-acl'\nacl.restrictWindowsPathSync(p, true)",
"import * as acl from '..\\\\shared\\\\secure-storage\\\\secure-path-windows-acl'\nacl.restrictWindowsPathSync(p, true)",
1,
['restrictWindowsPathSync']
],
@@ -148,7 +148,7 @@ describe('main sync-spawn ratchet', () => {
it('fails a lowered or stale count until it is pruned, and prune never raises', () => {
const write =
"import { restrictWindowsPathSync } from '../shared/secure-path-windows-acl'\nrestrictWindowsPathSync(a, b)\n"
"import { restrictWindowsPathSync } from '../shared/secure-storage/secure-path-windows-acl'\nrestrictWindowsPathSync(a, b)\n"
const root = tree({
'src/main/store.ts': write,
'src/main/clean.ts': 'export const done = true\n',
@@ -1,4 +1,4 @@
import { copyFileSync, mkdirSync, readFileSync } from 'node:fs'
import { copyFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'
import { dirname, join, relative } from 'node:path'
// Walk/copy relative modules instead of maintaining fixture list: omitted dependencies hide target failures behind resolution errors.
@@ -22,7 +22,9 @@ function collectScriptModules(scriptPath, seen = new Set()) {
/(?:\bfrom|\brequire\s*\(|\bimport\s*\(|\bimport)\s*'(\.\.?\/[^']+)'/g
)
for (const [, specifier] of specifiers) {
collectScriptModules(join(dirname(scriptPath), specifier), seen)
const modulePath = join(dirname(scriptPath), specifier)
const resolved = [modulePath, `${modulePath}.ts`].find((file) => existsSync(file)) ?? modulePath
collectScriptModules(resolved, seen)
}
return seen
}
@@ -33,10 +33,7 @@ describe('copyScriptWithLocalModules', () => {
it('preserves parent paths for modules shared with the runtime', () => {
const sourceDir = sourceTree({ 'runtime.ts': 'export const value = 42\n' })
mkdirSync(join(sourceDir, 'scripts'))
writeFileSync(
join(sourceDir, 'scripts', 'entry.mjs'),
"export { value } from '../runtime.ts'\n"
)
writeFileSync(join(sourceDir, 'scripts', 'entry.mjs'), "export { value } from '../runtime'\n")
const destinationRoot = mkdtempSync(join(fixtureDir, 'dest-'))
copyScriptWithLocalModules(
join(sourceDir, 'scripts', 'entry.mjs'),
@@ -431,15 +431,6 @@ export const PR_E2E_SOURCE_ROUTES = [
file
)
},
{
id: 'quick-open.paired-host-path-search',
specs: ['tests/e2e/paired-quick-open-large-tree.spec.ts'],
matches: (file) =>
isProductSource(file) &&
/^(?:src\/main\/ipc\/filesystem-(?:list-files|search-file-paths)\.ts|src\/main\/ripgrep\/bundled-ripgrep-path\.ts|src\/main\/providers\/(?:filesystem-provider-contract|ssh-filesystem-provider(?:-capabilities)?)\.ts|src\/main\/runtime\/(?:orca-runtime-files|rpc\/methods\/files)\.ts|src\/renderer\/src\/(?:components\/(?:QuickOpen|quick-open-file-list|quick-open-search)\.tsx?|runtime\/(?:files\/search\/runtime-file-search-client|runtime-legacy-quick-open-inventory)\.ts)|src\/shared\/(?:quick-open-(?:install-rg|path-search|transport-budget)|ripgrep-process-availability|bundled-ripgrep)\.ts)$/.test(
file
)
},
{
id: 'terminal-session.host-cold-park-stream-continuity',
specs: ['tests/e2e/host-parked-pane-remote-viewer.spec.ts'],
@@ -55,7 +55,7 @@ export const PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES = [
'src/preload/api/fs-bridge.ts',
'src/renderer/src/runtime/files/reads/runtime-file-range-preview.ts',
'src/renderer/src/runtime/files/reads/runtime-file-read-client.ts',
'src/shared/file-preview-kind.ts'
'src/shared/file-preview/file-preview-kind.ts'
].includes(file))
},
{
@@ -150,7 +150,6 @@ export function isCloudTestRunnerInput(file) {
// The package (windows) job's "Test Windows-specific boundaries" step runs exactly these files.
export const WINDOWS_BOUNDARY_TESTS = [
'src/main/zcode/zcode-plan-api-key-store-native-windows.test.ts',
'config/scripts/native-build/node-addons/rebuild-native-deps.test.mjs',
'config/scripts/native-build/node-addons/rebuild-native-deps-windows-process-tree.test.mjs',
'config/scripts/native-build/node-addons/rebuild-native-deps-node-pty.test.mjs',
@@ -212,8 +211,7 @@ export const WINDOWS_BOUNDARY_TESTS = [
'src/main/startup/windows-std-handle-inheritance.win32.test.ts',
'src/main/startup/windows-isolated-spawner.win32.test.ts',
'src/main/runtime/workspaces/catalog/worktree-scan-admin-fingerprint-gate.test.ts',
'src/shared/secure-file-fsync-flags.test.ts',
'src/shared/secure-path-windows-acl.win32.test.ts',
'src/shared/secure-storage/secure-path-windows-acl.win32.test.ts',
'src/main/runtime/rpc/server/pairing/unreadable-secret-store-preservation.win32.test.ts',
'src/main/ipc/preflight-provider-command-selection.test.ts',
'src/main/ipc/preflight-runnable-local-cli.test.ts',
+4 -1
View File
@@ -1,6 +1,9 @@
import { useMemo, useState } from 'react'
import { StyleSheet, View } from 'react-native'
import { readSvgIntrinsicSize, svgMarkupDataUri } from '../../../src/shared/svg-document'
import {
readSvgIntrinsicSize,
svgMarkupDataUri
} from '../../../src/shared/file-preview/svg-document'
import { useMobileTranslation } from '../i18n/use-mobile-translation'
import { MobileLoadErrorState } from './MobileStateView'
import { MobilePanZoomImage } from './MobilePanZoomImage'
@@ -5,7 +5,10 @@ import { colors, radii, spacing, typography, pressedStyle } from '../../theme/mo
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
import { themedStyleSheet } from '../../theme/themed-styles'
import { readableMermaidFlowchartSvg } from '../../../../src/shared/mermaid-flowchart-contrast'
import { readSvgIntrinsicSize, svgMarkupDataUri } from '../../../../src/shared/svg-document'
import {
readSvgIntrinsicSize,
svgMarkupDataUri
} from '../../../../src/shared/file-preview/svg-document'
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
import { MobileNativeChatImageViewer } from '../../session/native-chat/visual/MobileNativeChatImageViewer'
import { mermaidDiagramConfig } from './mermaid-diagram-config'
@@ -3,8 +3,8 @@ import { Platform, ScrollView, Text, View } from 'react-native'
import type {
AttachmentTextSource,
AttachmentTextWindow
} from '../../../src/shared/attachment-text-source'
import { AttachmentTextViewport } from '../../../src/shared/attachment-text-viewport'
} from '../../../src/shared/attachment-text/attachment-text-source'
import { AttachmentTextViewport } from '../../../src/shared/attachment-text/attachment-text-viewport'
import { chatAttachmentPreviewStyles as styles } from './mobile-file-preview-styles'
function scrollElement(view: ScrollView | null): HTMLElement | null {
@@ -8,7 +8,7 @@ import { AttachmentTextScrollView } from './AttachmentTextScrollView'
import { SafeAreaView } from 'react-native-safe-area-context'
import { useWorkspaceRouteHandoff } from '../navigation/workspace-route-handoff'
import { useWorkspaceClient } from '../transport/use-workspace-client'
import { createAttachmentTextPreviewHook } from '../../../src/shared/use-attachment-text-preview'
import { createAttachmentTextPreviewHook } from '../../../src/shared/attachment-text/use-attachment-text-preview'
import { chatTextAttachmentName } from '../../../src/shared/native-chat-text-attachment-references'
import { MOBILE_BRIDGE_MAX_FRAME_BYTES } from '../../../src/shared/mobile-bridge-frame-bytes'
import { useClipboardWriter } from '../platform/clipboard'
@@ -1,607 +0,0 @@
// @vitest-environment happy-dom
import { act, createElement, type ReactNode } from 'react'
import { createRoot } from 'react-dom/client'
import type { RpcResponse } from '../transport/types'
import type * as ReactNative from 'react-native'
import { expect, it, vi } from 'vitest'
import { MobileChatAttachmentPreview } from './MobileChatAttachmentPreview'
import { activateMobileUiLocale } from '../i18n/mobile-i18n'
import { useMobileFileTapHandlers } from '../session/use-mobile-file-tap-handlers'
import { MobileNativeChatComposerAttachments } from '../session/native-chat/composer/MobileNativeChatComposerAttachments'
import { MobileNativeChatOpenFileContext } from '../session/native-chat/mobile-native-chat-open-file-context'
import { normalizeMobileFilePreviewRouteParams } from './mobile-file-preview-route'
import { AttachmentTextSource } from '../../../src/shared/attachment-text-source'
vi.mock('react-native', () => vi.importActual<typeof ReactNative>('react-native-web'))
vi.mock('react-native-safe-area-context', () => ({
SafeAreaView: ({ children }: { children: ReactNode }) => createElement('div', null, children)
}))
vi.mock('../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => 'light' }))
const mocks = vi.hoisted(() => ({ send: vi.fn(), back: vi.fn(), write: vi.fn(), push: vi.fn() }))
vi.mock('../navigation/workspace-route-handoff', () => ({
useWorkspaceRouteHandoff: () => ({ back: mocks.back, push: mocks.push })
}))
vi.mock('../platform/clipboard', () => ({ useClipboardWriter: () => ({ writeText: mocks.write }) }))
const client = {
sendRequest: (...args: unknown[]) => mocks.send(...args),
getState: () => 'connected' as const,
getLastConnectedAt: () => 1,
getGeneration: () => 1
}
vi.mock('../transport/use-workspace-client', () => ({
useWorkspaceClient: () => ({ client, state: 'connected' })
}))
// This full RN-web flow awaits sequential real layouts across dense, elastic and UTF-8 sources.
it(
'opens the phone attachment card, scrolls the actual RN-web list to its tail and copies eligible complete text',
{ timeout: 15_000 },
async () => {
await activateMobileUiLocale('en')
let viewportHeight = 600
const children = (node: HTMLElement) =>
Array.from(node.children).filter(
(child): child is HTMLElement => child instanceof HTMLElement
)
const flowChildren = (node: HTMLElement) =>
children(node).filter((child) => getComputedStyle(child).position !== 'absolute')
const height = (node: HTMLElement): number => {
const style = getComputedStyle(node)
if (node.style.height.endsWith('px')) {
return Number.parseFloat(node.style.height)
}
if ([style.overflowX, style.overflowY].some((value) => ['auto', 'scroll'].includes(value))) {
return viewportHeight
}
const fixed = Number.parseFloat(style.height)
if (Number.isFinite(fixed)) {
return fixed
}
const children = flowChildren(node).map(height)
return Math.max(
Number.parseFloat(style.minHeight) || 0,
children.length
? style.flexDirection === 'row'
? Math.max(...children)
: children.reduce((sum, value) => sum + value, 0)
: node.children.length === 0 && node.textContent
? 19
: 0
)
}
const width = (node: HTMLElement): number => {
if (node.style.opacity === '0') {
return 8
}
const value = getComputedStyle(node).width
const fixed = Number.parseFloat(value)
const available = node.parentElement ? width(node.parentElement) : 390
return Number.isFinite(fixed)
? value.endsWith('%')
? (available * fixed) / 100
: fixed
: available
}
const descriptors = new Map<string, PropertyDescriptor | undefined>()
const descendantBottom = (node: HTMLElement): number => {
const style = getComputedStyle(node)
return [style.overflow, style.overflowY].some((value) =>
['hidden', 'clip', 'auto', 'scroll'].includes(value)
)
? height(node)
: Math.max(
height(node),
...children(node).map((child) => child.offsetTop + descendantBottom(child))
)
}
const metrics = {
offsetHeight: height,
clientHeight: height,
offsetWidth: width,
clientWidth: width,
scrollHeight: (node: HTMLElement) =>
Math.max(
height(node),
...children(node).map((child) => child.offsetTop + descendantBottom(child))
),
scrollWidth: (node: HTMLElement) =>
Math.max(width(node), ...flowChildren(node).map((child) => child.scrollWidth)),
offsetParent: (node: HTMLElement) => node.parentElement,
offsetLeft: (node: HTMLElement) => Number.parseFloat(getComputedStyle(node).left) || 0,
offsetTop: (node: HTMLElement) => {
const style = getComputedStyle(node)
if (style.position === 'absolute') {
return Number.parseFloat(style.top) || 0
}
const parent = node.parentElement
if (!parent || getComputedStyle(parent).flexDirection === 'row') {
return 0
}
const siblings = flowChildren(parent)
return siblings
.slice(0, siblings.indexOf(node))
.reduce((sum, sibling) => sum + height(sibling), 0)
}
}
for (const [name, measure] of Object.entries(metrics)) {
descriptors.set(name, Object.getOwnPropertyDescriptor(HTMLElement.prototype, name))
Object.defineProperty(HTMLElement.prototype, name, {
configurable: true,
get(this: HTMLElement) {
return measure(this)
}
})
}
const positions = new WeakMap<HTMLElement, number>()
const nativePositions = new WeakMap<HTMLElement, number>()
const horizontal = new WeakMap<HTMLElement, number>()
let deliverScroll = true
descriptors.set(
'scrollLeft',
Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollLeft')
)
Object.defineProperty(HTMLElement.prototype, 'scrollLeft', {
configurable: true,
get(this: HTMLElement) {
const left = Math.min(
horizontal.get(this) || 0,
Math.max(0, this.scrollWidth - this.clientWidth)
)
horizontal.set(this, left)
return left
},
set(this: HTMLElement, value: number) {
horizontal.set(this, Math.max(0, Math.min(value, this.scrollWidth - this.clientWidth)))
}
})
descriptors.set(
'scrollTop',
Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'scrollTop')
)
Object.defineProperty(HTMLElement.prototype, 'scrollTop', {
configurable: true,
get(this: HTMLElement) {
return (
nativePositions.get(this) ??
Math.min(positions.get(this) || 0, Math.max(0, this.scrollHeight - this.clientHeight))
)
},
set(this: HTMLElement, value: number) {
nativePositions.delete(this)
const top = Math.max(0, Math.min(value, this.scrollHeight - this.clientHeight))
if (top !== this.scrollTop) {
positions.set(this, top)
if (deliverScroll) {
queueMicrotask(() => this.dispatchEvent(new Event('scroll')))
}
}
}
})
const rect = vi
.spyOn(HTMLElement.prototype, 'getBoundingClientRect')
.mockImplementation(function (this: HTMLElement) {
let x = this.offsetLeft,
y = this.offsetTop
for (let parent = this.parentElement; parent; parent = parent.parentElement) {
x += parent.offsetLeft - parent.scrollLeft
y += parent.offsetTop - parent.scrollTop
}
return new DOMRect(x, y, width(this), height(this))
})
const NativeResizeObserver = globalThis.ResizeObserver
vi.stubGlobal(
'ResizeObserver',
class extends NativeResizeObserver {
constructor(private readonly notify: ResizeObserverCallback) {
super(notify)
}
observe(target: Element) {
super.observe(target)
const box = {
inlineSize: target.getBoundingClientRect().width,
blockSize: target.getBoundingClientRect().height
}
this.notify(
[
{
target,
contentRect: target.getBoundingClientRect(),
borderBoxSize: [box],
contentBoxSize: [box],
devicePixelContentBoxSize: [box]
}
],
this
)
}
}
)
const path = '/host/agent-session-attachments/12345678-1234-1234-1234-123456789abc/report.txt'
let content = Buffer.from(`${'\n'.repeat(25 * 1024 * 1024)}TAIL`)
const sourceBlocks = vi.spyOn(AttachmentTextSource.prototype, 'block')
const reads: { offset: number; length: number }[] = []
let hold: Promise<void> | undefined
const held = Promise.withResolvers<void>()
const release = Promise.withResolvers<void>()
mocks.send.mockImplementation(
async (
method: string,
request?: { offset: number; length: number }
): Promise<RpcResponse> => {
if (method === 'status.get') {
return {
id: 's',
ok: true,
result: { capabilities: ['native-chat.text-attachment-read.v1'] }
}
}
if (!request) {
throw new Error('Expected actual range')
}
reads.push(request)
if (hold && request.offset > 0) {
held.resolve()
await hold
}
const part = content.subarray(request.offset, request.offset + request.length)
return {
id: 'r',
ok: true,
result: {
snapshot: 'a'.repeat(64),
size: content.length,
bytesRead: part.length,
contentBase64: part.toString('base64'),
eof: request.offset + part.length === content.length
}
}
}
)
function Card() {
const handlers = useMobileFileTapHandlers({
client,
hostId: 'owner',
worktreeId: 'folder:work',
worktreeName: 'Work',
nativeChatSessionId: 's',
structuredAttachments: true,
activeHandleRef: { current: null },
terminalCwdRef: { current: new Map() },
openBrowser: vi.fn(),
fetchSessionTabs: async () => {},
getSessionTabs: () => [],
getActiveSessionTabId: () => 'chat',
getActiveSessionTabType: () => 'agent-session',
switchSessionTab: vi.fn(),
scheduleDelayedAction: vi.fn(),
reportChatTapFailure: vi.fn(),
getSendCompletionGeneration: () => 0
})
return createElement(
MobileNativeChatOpenFileContext,
{ value: handlers.handleNativeChatFileTap },
createElement(MobileNativeChatComposerAttachments, {
images: [],
files: [
{ id: 'file', name: 'report.txt', mime: 'text/plain', byteLength: content.length, path }
]
})
)
}
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const button = (name: string) => {
const element = Array.from(container.querySelectorAll('[role="button"]')).find(
(node) => node.textContent === name
)
if (!(element instanceof HTMLElement)) {
throw new Error(`Missing ${name}`)
}
return element
}
const flush = () => act(async () => {})
try {
await act(async () => root.render(createElement(Card)))
const card = container.querySelector('[role="button"]')
if (!(card instanceof HTMLElement)) {
throw new Error('Missing real attachment card')
}
act(() => card.click())
const route = normalizeMobileFilePreviewRouteParams(mocks.push.mock.calls[0][0].params)
if (!route.ok) {
throw new Error('Expected structured attachment route')
}
expect(route.params.absolutePath).toBe(path)
await act(async () =>
root.render(createElement(MobileChatAttachmentPreview, { params: route.params }))
)
// Supply browser layout, not source results or callbacks; the real list owns scrolling and demand.
const scroller = Array.from(container.querySelectorAll('div')).find((node) =>
['auto', 'scroll'].includes(getComputedStyle(node).overflowY)
)
if (!(scroller instanceof HTMLElement)) {
throw new Error('Expected actual RN-web scroll host')
}
await vi.waitFor(async () => {
await flush()
expect(scroller.offsetHeight).toBe(viewportHeight)
expect(scroller.offsetWidth).toBeGreaterThan(0)
expect(reads.length).toBeGreaterThan(0)
// Visible rows prove the async RN-web onLayout and initial source publication have settled.
expect(
container.querySelectorAll('[data-testid="attachment-text-segment"]').length
).toBeGreaterThan(Math.floor(viewportHeight / 19))
})
expect(button('Copy').getAttribute('aria-disabled')).toBe('true')
expect(button('Save').getAttribute('aria-disabled')).toBe('true')
const source = sourceBlocks.mock.contexts.at(-1)
if (!(source instanceof AttachmentTextSource)) {
throw new Error('Expected actual source identity')
}
const { AttachmentTextViewport } =
await import('../../../src/shared/attachment-text-viewport')
const track = new AttachmentTextViewport(source, 19, scroller.clientHeight)
await act(async () => {
scroller.scrollTop = track.total - scroller.clientHeight
scroller.dispatchEvent(new Event('scroll'))
})
await vi.waitFor(async () => {
await flush()
expect(container.textContent).toContain('TAIL')
expect(scroller.scrollTop + scroller.clientHeight).toBe(scroller.scrollHeight)
})
expect(container.querySelectorAll('input')).toHaveLength(0)
expect(reads.every((request) => request.length <= 16 * 1024)).toBe(true)
expect(
container.querySelectorAll('[data-testid="attachment-text-segment"]').length
).toBeGreaterThan(0)
expect(
container.querySelectorAll('[data-testid="attachment-text-segment"]').length
).toBeLessThanOrEqual(Math.ceil(viewportHeight / 19) + 4)
// Discover enough real ranges through scrolling to exercise a compressed physical track.
for (let block = 1; block < 32; block++) {
const current = new AttachmentTextViewport(source, 19, scroller.clientHeight)
if (current.scale < 1) {
break
}
await act(async () => {
scroller.scrollTop = current.position({ block, row: 1 })
scroller.dispatchEvent(new Event('scroll'))
})
await vi.waitFor(async () => {
await flush()
expect(source.rowKnown(block)).toBe(true)
})
}
const compressed = new AttachmentTextViewport(source, 19, scroller.clientHeight)
expect(compressed.scale).toBeLessThan(1)
await act(async () => {
scroller.scrollTop = compressed.total - compressed.height - 1
scroller.dispatchEvent(new Event('scroll'))
})
await vi.waitFor(async () => {
await flush()
const rows = Array.from(
container.querySelectorAll<HTMLElement>('[data-testid="attachment-text-segment"]')
)
const declared = Number.parseFloat(rows[0]!.parentElement!.style.height)
expect(container.textContent).toContain('TAIL')
expect(Math.max(...rows.map((row) => row.offsetTop + row.offsetHeight))).toBeGreaterThan(
declared
)
expect(scroller.scrollHeight).toBe(Math.max(scroller.clientHeight, declared))
})
await act(async () => {
scroller.scrollTop = 0
scroller.dispatchEvent(new Event('scroll'))
})
await act(async () => button('Back').click())
expect(mocks.back).toHaveBeenCalledOnce()
content = Buffer.from('x'.repeat(96 * 1024))
await act(async () =>
root.render(
createElement(MobileChatAttachmentPreview, { key: 'motion', params: route.params })
)
)
await vi.waitFor(async () => {
await flush()
expect(
container.querySelector('[data-testid="attachment-text-segment"]')?.textContent
).toBe('x'.repeat(256))
})
const motion = Array.from(container.querySelectorAll('div')).find((node) =>
['auto', 'scroll'].includes(getComputedStyle(node).overflowY)
)
if (!(motion instanceof HTMLElement)) {
throw new Error('Missing actual vertical host')
}
let outer = motion.parentElement
while (outer && !['auto', 'scroll'].includes(getComputedStyle(outer).overflowX)) {
outer = outer.parentElement
}
if (!outer) {
throw new Error('Missing actual horizontal host')
}
const hostScroll = vi.spyOn(motion, 'scrollTo')
try {
outer.scrollLeft = 500
hold = release.promise
await act(async () => {
motion.scrollTop = 3000
})
await held.promise
expect(outer.scrollLeft).toBe(500)
deliverScroll = false
motion.scrollTop += 80
const live = motion.scrollTop
const calls = hostScroll.mock.calls.length
hold = undefined
await act(async () => release.resolve())
await vi.waitFor(async () => {
await flush()
expect(
container.querySelector('[data-testid="attachment-text-segment"]')?.textContent
).toBe('x'.repeat(256))
})
expect(hostScroll.mock.calls.length).toBe(calls)
expect(motion.scrollTop).toBe(live)
expect(outer.scrollLeft).toBe(500)
deliverScroll = true
await act(async () => {
motion.scrollTop = 0
motion.dispatchEvent(new Event('scroll'))
})
await vi.waitFor(async () => {
await flush()
expect(motion.scrollTop).toBe(0)
expect(
container.querySelector('[data-testid="attachment-text-segment"]')?.textContent
).toBe('x'.repeat(256))
})
expect(outer.scrollLeft).toBe(500)
} finally {
release.resolve()
deliverScroll = true
hostScroll.mockRestore()
}
viewportHeight = 645
const line = 'Original pasted contents 35636; exact Copy and Save.\n'
const header = `COPY35636-START\n indented\tfield value; whitespace35636\n ${line}`
const tail = '\nCOPY35636-END\n'
content = Buffer.from((header + line.repeat(2000)).slice(0, 98304 - tail.length) + tail)
await act(async () =>
root.render(
createElement(MobileChatAttachmentPreview, { key: 'elastic', params: route.params })
)
)
await vi.waitFor(async () => {
await flush()
expect(container.textContent).toContain('COPY35636-START')
})
const elasticSource = sourceBlocks.mock.contexts.at(-1)
const elastic = Array.from(container.querySelectorAll('div')).find((node) =>
['auto', 'scroll'].includes(getComputedStyle(node).overflowY)
)
if (!(elasticSource instanceof AttachmentTextSource) || !(elastic instanceof HTMLElement)) {
throw new Error('Missing actual literal source/host')
}
await vi.waitFor(async () => {
await flush()
expect(elastic.clientHeight).toBe(645)
})
for (let block = 1; block < elasticSource.blockCount; block++) {
const current = new AttachmentTextViewport(elasticSource, 19, elastic.clientHeight)
await act(async () => {
elastic.scrollTop = current.position({ block, row: 1 })
elastic.dispatchEvent(new Event('scroll'))
})
await vi.waitFor(async () => {
await flush()
expect(elasticSource.rowKnown(block)).toBe(true)
})
}
const elasticTrack = new AttachmentTextViewport(elasticSource, 19, elastic.clientHeight)
expect(elasticTrack.total).toBe(35283)
const nativeScroll = async (top: number) =>
act(async () => {
nativePositions.set(elastic, top)
elastic.dispatchEvent(new Event('scroll'))
})
const elasticWrites = vi.spyOn(elastic, 'scrollTo')
try {
const writes = elasticWrites.mock.calls.length
for (const top of [35545, 34931]) {
await nativeScroll(top)
await vi.waitFor(async () => {
await flush()
const rows = Array.from(
container.querySelectorAll<HTMLElement>('[data-testid="attachment-text-segment"]')
)
expect(rows[0]?.offsetTop).toBe(34637)
expect(rows.at(-1)!.offsetTop + rows.at(-1)!.offsetHeight).toBe(35283)
expect(elastic.scrollHeight).toBe(35283)
})
}
await nativeScroll(34638 - 645)
await vi.waitFor(async () => {
await flush()
expect(
container.querySelector<HTMLElement>('[data-testid="attachment-text-segment"]')!
.offsetTop
).toBeLessThan(34637)
})
expect(elasticWrites.mock.calls.length).toBe(writes)
} finally {
elasticWrites.mockRestore()
}
viewportHeight = 600
content = Buffer.from('🙂'.repeat((25 * 1024 * 1024) / 4))
await act(async () =>
root.render(
createElement(MobileChatAttachmentPreview, { key: 'unicode', params: route.params })
)
)
await vi.waitFor(async () => {
await flush()
const rows = container.querySelectorAll('[data-testid="attachment-text-segment"]')
expect(rows.length).toBeGreaterThanOrEqual(Math.ceil(viewportHeight / 19))
expect(rows.length).toBeLessThanOrEqual(Math.ceil(viewportHeight / 19) + 4)
expect(rows[0]?.textContent).toBe('🙂'.repeat(256))
})
const literal = ' indented\tfield value'
content = Buffer.from(`\ufeffcomplete\r\n${literal}\n🙂`)
await act(async () =>
root.render(
createElement(MobileChatAttachmentPreview, { key: 'small', params: route.params })
)
)
await vi.waitFor(async () => {
await flush()
expect(button('Copy').getAttribute('aria-disabled')).not.toBe('true')
const row = Array.from(
container.querySelectorAll('[data-testid="attachment-text-segment"]')
).find((node) => node.textContent === literal)
if (!(row instanceof HTMLElement)) {
throw new Error('Missing literal indented text row')
}
expect(getComputedStyle(row).whiteSpace).toBe('pre')
})
await act(async () => button('Copy').click())
expect(mocks.write).toHaveBeenCalledWith(content.toString('utf8'))
content = Buffer.from('"'.repeat(400_000))
await act(async () =>
root.render(
createElement(MobileChatAttachmentPreview, { key: 'escaped', params: route.params })
)
)
await vi.waitFor(async () => {
await flush()
expect(button('Copy').getAttribute('aria-disabled')).not.toBe('true')
})
await act(async () => button('Copy').click())
expect(container.textContent).toContain(
'Full Copy for this attachment needs the upcoming phone update.'
)
expect(mocks.write).toHaveBeenCalledTimes(1)
} finally {
release.resolve()
try {
await act(async () => root.unmount())
} finally {
container.remove()
sourceBlocks.mockRestore()
rect.mockRestore()
for (const [name, descriptor] of descriptors) {
if (descriptor) {
Object.defineProperty(HTMLElement.prototype, name, descriptor)
} else {
Reflect.deleteProperty(HTMLElement.prototype, name)
}
}
vi.unstubAllGlobals()
}
}
}
)
+2 -2
View File
@@ -1,5 +1,5 @@
import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/media-file-extensions'
import { compareFileNames } from '../../../src/shared/file-name-sort'
import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/file-preview/media-mime-types'
import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort'
export type MobileDirEntry = {
name: string
@@ -1,125 +0,0 @@
import { expect, it, vi } from 'vitest'
import { createMobileChatAttachmentReader } from './mobile-chat-attachment-read'
import { AttachmentTextSource } from '../../../src/shared/attachment-text-source'
import { AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY } from '../../../src/shared/agent-session/agent-session-runtime-capabilities'
import { RpcClientRequestTracker } from '../transport/rpc-client-request-tracker'
import { RpcClientConnectionState } from '../transport/rpc-client-connection-state'
import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client'
import { scopeRpcClientToExecutionHost } from '../transport/execution-host-scoped-rpc-client'
import type { SendRequestOptions } from '../transport/rpc-client'
import type { RpcRequestFrame } from '../transport/rpc-envelope-fields'
function fixture() {
const state = new RpcClientConnectionState({
endpoint: 'ws://test35636',
getReconnectAttempt: () => 0,
isClosed: () => false
})
state.publish('connected')
const frames: RpcRequestFrame[] = []
const control: {
capable: boolean
holdStatus: boolean
holdBody: boolean
atConnected: (() => void) | undefined
body: unknown
} = {
capable: true,
holdStatus: false,
holdBody: false,
atConnected: undefined,
body: {
snapshot: 'a'.repeat(64),
size: 1,
bytesRead: 1,
contentBase64: 'eA==',
eof: true
}
}
let serial = 0
let currentMethod = ''
const answer = (frame: RpcRequestFrame, runtimeId = 'successor') =>
tracker.resolve({
id: frame.id,
ok: true,
result:
frame.method === 'status.get'
? { capabilities: control.capable ? [AGENT_SESSION_TEXT_ATTACHMENT_READ_CAPABILITY] : [] }
: control.body,
_meta: { runtimeId }
})
const tracker = new RpcClientRequestTracker({
nextId: () => String(++serial),
getState: () => state.get(),
waitForConnected: (timeout) => {
const connected = state.waitForConnected(timeout)
return currentMethod === 'agentSessionAttachment.readTextChunk' && control.atConnected
? connected.then(control.atConnected)
: connected
},
sendFrame: (frame) => {
frames.push(frame)
if (!(frame.method === 'status.get' ? control.holdStatus : control.holdBody)) {
queueMicrotask(() => answer(frame))
}
return true
}
})
const physical = {
sendRequest: (method: string, params?: unknown, options?: SendRequestOptions) => {
currentMethod = method
return tracker.sendRequest(method, params, options)
},
getState: () => state.get(),
getLastConnectedAt: () => state.getLastConnectedAt(),
getReconnectAttempt: () => 0,
onStateChange: (listener: Parameters<typeof state.addListener>[0]) =>
state.addListener(listener),
notifyForeground: () => {},
close: () => tracker.rejectAll('closed'),
subscribe: () => () => {},
updateTerminalSubscriptionViewport: () => {}
}
const logical = createStableLogicalRpcClient(physical, 'lan')
const client = scopeRpcClientToExecutionHost(logical, 'runtime:server35636')
const source = (read = createMobileChatAttachmentReader(client)) =>
new AttachmentTextSource('/source35636', read)
const bodyCount = () =>
frames.filter((frame) => frame.method === 'agentSessionAttachment.readTextChunk').length
return { state, frames, control, answer, tracker, physical, logical, client, source, bodyCount }
}
it('settles an abandoned status waiter before release and keeps its same-reader successor pinned', async () => {
const count = 1
const f = fixture()
f.control.holdStatus = true
const readers = Array.from({ length: count }, () => createMobileChatAttachmentReader(f.client))
const old = readers.map(f.source)
const pending = old.map((source) => source.block(0).catch((error) => error))
await vi.waitFor(() => expect(f.frames).toHaveLength(count))
const held = [...f.frames]
old.forEach((source) => source.dispose())
expect((await Promise.all(pending)).map((error) => error.name)).toEqual(
Array(count).fill('AbortError')
)
expect(f.tracker.size()).toBe(0)
f.control.holdStatus = false
const successors = readers.map(f.source)
await Promise.all(successors.map((source) => source.block(0)))
expect(f.bodyCount()).toBe(count)
held.forEach((frame) => expect(f.answer(frame, 'disposed')).toBe(false))
expect(f.bodyCount()).toBe(count)
expect(await Promise.all(successors.map((source) => source.copyText()))).toEqual(
Array(count).fill('x')
)
expect(f.frames.every((frame) => !('signal' in frame) && !('beforeSend' in frame))).toBe(true)
expect(
f.frames.every(
(frame) =>
JSON.stringify(frame.envelope) === JSON.stringify({ executionHost: 'runtime:server35636' })
)
).toBe(true)
successors.forEach((source) => source.dispose())
f.logical.close()
})
@@ -6,7 +6,7 @@ import { rpcResultVariant } from '../transport/rpc-operation-result-reader'
import {
attachmentTextChunkSchema,
type AttachmentTextRead
} from '../../../src/shared/attachment-text-source'
} from '../../../src/shared/attachment-text/attachment-text-source'
import type { RpcClient } from '../transport/rpc-client'
import type { RpcOperationSender } from '../transport/rpc-operation-sender'
@@ -1,4 +1,4 @@
import { buildImageDataUri } from '../../../src/shared/image-data-uri'
import { buildImageDataUri } from '../../../src/shared/file-preview/image-data-uri'
// Only modifiedDeleted proves deletion; read failures can also return empty modifiedContent with modifiedIsBinary false.
// Omit kind: the reply reader admits every non-text arm, including unknown host arms.
@@ -4,8 +4,8 @@ import type { RpcClient } from '../transport/rpc-client'
import { isMobileMethodUnavailableError } from '../transport/mobile-method-unavailable'
import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc-operation'
import { rpcResultVariant, rpcResultVariants } from '../transport/rpc-operation-result-reader'
import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-dir-page'
import { compareDirEntries } from '../../../src/shared/file-name-sort'
import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-listing/file-dir-page'
import { compareDirEntries } from '../../../src/shared/file-listing/file-name-sort'
import {
fileDirectoryEntriesSchema,
fileDirectoryPageSchema,
+1 -1
View File
@@ -1,4 +1,4 @@
import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/media-file-extensions'
import { MEDIA_FILE_MIME_TYPES } from '../../../src/shared/file-preview/media-mime-types'
export const PDF_MIME_TYPE = 'application/pdf'
@@ -1,9 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { SshConnectionState } from '../../../src/shared/ssh-types'
import {
FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY,
FILE_MUTATION_OWNERSHIP_UPDATE_REQUIRED_MESSAGE
} from '../../../src/shared/protocol-version'
import { FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY } from '../../../src/shared/file-access/files-runtime-capabilities'
import type { RpcClient } from '../transport/rpc-client'
import type { RpcResponse } from '../transport/types'
import {
@@ -70,41 +67,6 @@ describe('mobile file mutation ownership', () => {
)
})
it('captures local ownership only after verifying the runtime capability', async () => {
const { client, sendRequest } = clientWithResponses([
success({ capabilities: [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] }),
success({ worktree: { hostId: 'local' } })
])
await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).resolves.toEqual({
expectedExecutionHostId: 'local'
})
expect(sendRequest.mock.calls).toEqual([
['status.get', undefined, { timeoutMs: 15_000 }],
['worktree.show', { worktree: 'id:worktree-1' }, { timeoutMs: 15_000 }]
])
})
it('captures SSH generation from the HUB before building mutation params', async () => {
const state = sshState('target-1', 9)
const { client, sendRequest } = clientWithResponses([
success({ capabilities: [FILE_MUTATION_OWNERSHIP_RUNTIME_CAPABILITY] }),
success({ worktree: { hostId: 'ssh:target-1' } }),
success({ state })
])
await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).resolves.toEqual({
expectedExecutionHostId: 'ssh:target-1',
expectedSshTargetId: 'target-1',
expectedSshConnectionGeneration: 9
})
expect(sendRequest.mock.calls[2]).toEqual([
'ssh.getState',
{ targetId: 'target-1' },
{ timeoutMs: 15_000 }
])
})
// Absent hostId captures local; explicit null refuses an unplaceable host instead of sending its write locally.
it('captures local ownership for a workspace whose reply records no host', async () => {
const { client } = clientWithResponses([
@@ -127,13 +89,4 @@ describe('mobile file mutation ownership', () => {
"Couldn't verify the SSH connection"
)
})
it('refuses older runtimes before reading or mutating workspace files', async () => {
const { client, sendRequest } = clientWithResponses([success({ capabilities: [] })])
await expect(captureMobileFileMutationOwnership(client, 'id:worktree-1')).rejects.toThrow(
FILE_MUTATION_OWNERSHIP_UPDATE_REQUIRED_MESSAGE
)
expect(sendRequest).toHaveBeenCalledTimes(1)
})
})
@@ -1,5 +1,5 @@
import { parseExecutionHostId } from '../../../src/shared/execution-host'
import { assertFileMutationOwnershipCapability } from '../../../src/shared/file-mutation-ownership'
import { assertFileMutationOwnershipCapability } from '../../../src/shared/file-write/file-mutation-ownership'
import type { SshConnectionState, SshMutationExpectation } from '../../../src/shared/ssh-types'
import { translate } from '../i18n/mobile-i18n'
import {
+1 -1
View File
@@ -1,5 +1,5 @@
import { mobileFileMedia, type MobileFileMedia } from './mobile-file-media'
import { buildImageDataUri } from '../../../src/shared/image-data-uri'
import { buildImageDataUri } from '../../../src/shared/file-preview/image-data-uri'
import { classifyMobileArtifact } from '../session/mobile-artifact-kind'
import { buildMobileDiffLines, type MobileDiffLine } from '../session/mobile-diff-lines'
import { mobileDiffImageDataUri } from './mobile-diff-image-preview'
@@ -7,7 +7,7 @@ import { routeMarkdownHref } from '../components/markdown-href-routing'
import type { MobileFilePreviewRpcSender } from './mobile-file-preview-operations'
import { loadMobileFilePreview } from './mobile-file-preview-request'
import { classifyMobileArtifact } from '../session/mobile-artifact-kind'
import { svgMarkupDataUri } from '../../../src/shared/svg-document'
import { svgMarkupDataUri } from '../../../src/shared/file-preview/svg-document'
// Absolute paths leave the workspace; an external-file tab's document has no workspace images.
function isOutsideWorkspace(path: string): boolean {
@@ -1,4 +1,4 @@
import type { RuntimeNativeChatFileContext } from '../../../src/shared/runtime-types'
import type { RuntimeNativeChatFileContext } from '../../../src/shared/native-chat/native-chat-file-context'
import type { RpcFailure } from '../transport/types'
import {
terminalArtifactPathResolve,
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-dir-page'
import { FILE_READ_DIR_MAX_PAGE_ENTRIES } from '../../../src/shared/file-listing/file-dir-page'
import { hostQueryKey, type HostQueryTarget } from '../query/host-query-key'
import { hostReadClient } from '../query/host-read-client'
import type { RpcClient } from '../transport/rpc-client'
@@ -1,6 +1,6 @@
import * as z from 'zod'
import { CLIPBOARD_IMAGE_MAX_SOURCE_BYTES } from '../../../../src/shared/clipboard-image'
import { isKnownRasterImageMimeType } from '../../../../src/shared/raster-image-preview-limits'
import { isKnownRasterImageMimeType } from '../../../../src/shared/file-preview/raster-image-preview-limits'
import { MOBILE_CLIPBOARD_IMAGE_UPLOAD_CHUNK_BASE64_CHARS } from '../../session/mobile-clipboard-image-upload-chunk'
// The page cannot reach the clipboard, Photos or the share sheet from the WebView, so it hands the image to the shell.
+3 -3
View File
@@ -3,9 +3,9 @@ import {
agentSessionAttachmentAppends,
base64DecodedByteLength
} from '../../../src/shared/agent-session/agent-session-attachments'
import { readRasterImageDataUri } from '../../../src/shared/image-data-uri'
import { isKnownRasterImageMimeType } from '../../../src/shared/raster-image-preview-limits'
import { isSvgFilePath } from '../../../src/shared/svg-document'
import { readRasterImageDataUri } from '../../../src/shared/file-preview/image-data-uri'
import { isKnownRasterImageMimeType } from '../../../src/shared/file-preview/raster-image-preview-limits'
import { isSvgFilePath } from '../../../src/shared/file-preview/svg-document'
import type {
BridgeImageOperation,
BridgeImageRunParams
+1 -1
View File
@@ -8,7 +8,7 @@ import {
CLIPBOARD_IMAGE_MAX_SOURCE_BYTES,
CLIPBOARD_IMAGE_TOO_LARGE_ERROR
} from '../../../src/shared/clipboard-image'
import { isKnownRasterImageMimeType } from '../../../src/shared/raster-image-preview-limits'
import { isKnownRasterImageMimeType } from '../../../src/shared/file-preview/raster-image-preview-limits'
import {
imageParamsSchema,
type BridgeImageRunParams
@@ -1,4 +1,4 @@
import { compareFileNames } from '../../../src/shared/file-name-sort'
import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort'
import { translate } from '../i18n/mobile-i18n'
import type {
DiffComment,
+2 -4
View File
@@ -1,8 +1,6 @@
import type { ParsedFileLinkLocation } from '../../../src/shared/file-links/file-link-location'
import type {
RuntimeNativeChatFileContext,
RuntimeTerminalPathResolution
} from '../../../src/shared/runtime-types'
import type { RuntimeNativeChatFileContext } from '../../../src/shared/native-chat/native-chat-file-context'
import type { RuntimeTerminalPathResolution } from '../../../src/shared/terminal/runtime-terminal-file-path'
import { filesystemPathToFileUri } from '../../../src/shared/file-links/file-uri-path'
import { createMobileFilePreviewHref } from '../files/mobile-file-preview-route'
import { classifyMobileArtifact } from './mobile-artifact-kind'
@@ -11,7 +11,7 @@ import {
import {
getPreparedQuickOpenFiles,
rankQuickOpenFiles
} from '../../../../../src/shared/quick-open-path-search'
} from '../../../../../src/shared/quick-open/quick-open-path-search'
const FILE_SEARCH_DEBOUNCE_MS = 120
const FILE_SEARCH_RESULT_LIMIT = 16
@@ -30,9 +30,9 @@ import { nativeChatHostStatusCopy } from './native-chat-notice-copy'
import { pressedStyle } from '../../../theme/mobile-theme'
import { routeNativeChatHref } from '../../../../../src/shared/native-chat/native-chat-href-routing'
import { isRuntimePathAbsolute } from '../../../../../src/shared/cross-platform-path'
import { isRasterImagePath } from '../../../../../src/shared/file-preview-kind'
import { isKnownRasterImageMimeType } from '../../../../../src/shared/raster-image-preview-limits'
import { isSvgFilePath } from '../../../../../src/shared/svg-document'
import { isRasterImagePath } from '../../../../../src/shared/file-preview/file-preview-kind'
import { isKnownRasterImageMimeType } from '../../../../../src/shared/file-preview/raster-image-preview-limits'
import { isSvgFilePath } from '../../../../../src/shared/file-preview/svg-document'
/** Raster https, data and absolute-path images draw on the phone (paths through the chat's host); anything else stays a link.
* The shell's CSP refuses plain http, and React Native's Image cannot draw SVG. */
@@ -13,7 +13,7 @@ import {
import {
createPathExistenceBatch,
requirePathExistenceResults
} from '../../../../src/shared/path-existence-batch'
} from '../../../../src/shared/file-access/path-existence-batch'
import { resolveTerminalFileLink } from '../../../../src/shared/terminal/links/terminal-links'
import { getRepoIdFromWorktreeId } from '../../../../src/shared/worktree/id'
import {
@@ -1,4 +1,4 @@
import { buildImageDataUri } from '../../../../../src/shared/image-data-uri'
import { buildImageDataUri } from '../../../../../src/shared/file-preview/image-data-uri'
import { isAgentSessionAttachmentStorePath } from '../../../../../src/shared/agent-session/agent-session-attachments'
import { PrioritySemaphore } from '../../../../../src/shared/priority-semaphore'
import { filePreviewImageSchema } from '../../../files/file-preview-reply-schema'
@@ -1,4 +1,4 @@
import { compareFileNames } from '../../../src/shared/file-name-sort'
import { compareFileNames } from '../../../src/shared/file-listing/file-name-sort'
import { translate } from '../i18n/mobile-i18n'
import type {
MobileGitBranchChangeEntry,
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts'
import type { ArtifactListItem, ArtifactListPage } from '../shared/artifacts/artifacts'
export function formatArtifactList(artifacts: readonly ArtifactListItem[]): string {
if (artifacts.length === 0) {
-220
View File
@@ -1,220 +0,0 @@
import { mkdtemp, open, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ArtifactListItem } from '../../shared/artifacts'
import { ARTIFACT_HANDLERS } from './artifacts'
import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts'
import {
ARTIFACT_SHARING_DISABLED_CODE,
ARTIFACT_SHARING_DISABLED_NEXT_STEPS
} from '../../shared/artifact-sharing-gate'
const item: ArtifactListItem = {
artifact: {
version: 1,
slug: 'artifact-1',
title: null,
originalFileName: 'report.html',
sourceContentType: 'text/html',
renderedContentType: 'text/html',
createdAt: '2026-08-06T00:00:00.000Z',
updatedAt: '2026-08-06T00:00:00.000Z',
expiresAt: '2026-09-06T00:00:00.000Z',
byteSize: 12,
deletedAt: null
},
shareUrl: 'https://share.onorca.dev/a/artifact-1'
}
afterEach(async () => {
vi.restoreAllMocks()
await Promise.all(directories.splice(0).map((path) => rm(path, { recursive: true, force: true })))
})
const directories: string[] = []
async function artifactDirectory(): Promise<string> {
const path = await mkdtemp(join(tmpdir(), 'orca-artifact-cli-'))
directories.push(path)
return path
}
describe('artifact CLI handlers', () => {
it('reads a relative HTML file and sends its content to the runtime', async () => {
const cwd = await artifactDirectory()
await writeFile(join(cwd, 'report.html'), '<h1>Hi</h1>', 'utf8')
const call = vi.fn().mockResolvedValue({
id: 'request-1',
ok: true,
result: { status: 'ok', value: item },
_meta: { runtimeId: 'runtime-1' }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
await ARTIFACT_HANDLERS['artifacts share']!({
client: { call } as never,
cwd,
flags: new Map([['file', 'report.html']]),
json: false
})
expect(call).toHaveBeenCalledWith(
'artifacts.share',
expect.objectContaining({
sourceKey: join(cwd, 'report.html'),
content: '<h1>Hi</h1>',
contentType: 'text/html',
fileName: 'report.html'
})
)
expect(log).toHaveBeenCalledWith(item.shareUrl)
})
it('rejects unsupported file extensions before calling the runtime', async () => {
const cwd = await artifactDirectory()
await writeFile(join(cwd, 'report.txt'), 'hello', 'utf8')
const call = vi.fn()
await expect(
ARTIFACT_HANDLERS['artifacts share']!({
client: { call } as never,
cwd,
flags: new Map([['file', 'report.txt']]),
json: false
})
).rejects.toThrow(/HTML or Markdown/)
expect(call).not.toHaveBeenCalled()
})
it('rejects a sparse oversized file before attempting the RPC', async () => {
const cwd = await artifactDirectory()
const handle = await open(join(cwd, 'oversized.html'), 'w')
await handle.truncate(ARTIFACT_CLI_MAX_RPC_BYTES + 1)
await handle.close()
const call = vi.fn().mockResolvedValue({
id: 'request-1',
ok: true,
result: { settings: { artifactSharingEnabled: true } },
_meta: { runtimeId: 'runtime-1' }
})
await expect(
ARTIFACT_HANDLERS['artifacts share']!({
client: { call } as never,
cwd,
flags: new Map([['file', 'oversized.html']]),
json: false
})
).rejects.toThrow(/too large/)
expect(call).not.toHaveBeenCalledWith('artifacts.share', expect.anything())
})
it('passes an opaque list cursor through and prints the next cursor', async () => {
const call = vi.fn().mockResolvedValue({
id: 'request-1',
ok: true,
result: {
status: 'ok',
value: { artifacts: [item], nextCursor: 'next opaque page' }
},
_meta: { runtimeId: 'runtime-1' }
})
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
await ARTIFACT_HANDLERS['artifacts list']!({
client: { call } as never,
cwd: '/repo',
flags: new Map([['cursor', 'current opaque page']]),
json: false
})
expect(call).toHaveBeenCalledWith('artifacts.list', { cursor: 'current opaque page' })
expect(log).toHaveBeenCalledWith(
expect.stringContaining('More artifacts: --cursor next opaque page')
)
})
it.each(['artifacts share', 'artifacts update'])(
'denies `%s` from the capability preflight without reading or shipping the file',
async (command) => {
const cwd = await artifactDirectory()
const call = vi.fn().mockResolvedValue({
id: 'request-1',
ok: true,
result: { settings: { artifactSharingEnabled: false } },
_meta: { runtimeId: 'runtime-1' }
})
await expect(
ARTIFACT_HANDLERS[command]!({
client: { call } as never,
cwd,
flags: new Map([['file', 'report.html']]),
json: false
})
).rejects.toMatchObject({
code: ARTIFACT_SHARING_DISABLED_CODE,
data: { nextSteps: [...ARTIFACT_SHARING_DISABLED_NEXT_STEPS] }
})
expect(call).toHaveBeenCalledExactlyOnceWith('settings.get')
}
)
it.each([
['omits the capability field', {}],
['cannot answer the preflight', null]
])('still attempts the publish RPC when the host %s', async (_label, settings) => {
const cwd = await artifactDirectory()
await writeFile(join(cwd, 'report.html'), '<h1>Hi</h1>', 'utf8')
const call = vi.fn().mockImplementation((method: string) => {
if (method === 'settings.get') {
if (!settings) {
return Promise.reject(new Error('unsupported_method'))
}
return Promise.resolve({
id: 'request-1',
ok: true,
result: { settings },
_meta: { runtimeId: 'runtime-1' }
})
}
return Promise.resolve({
id: 'request-2',
ok: true,
result: { status: 'ok', value: item },
_meta: { runtimeId: 'runtime-1' }
})
})
vi.spyOn(console, 'log').mockImplementation(() => undefined)
await ARTIFACT_HANDLERS['artifacts share']!({
client: { call } as never,
cwd,
flags: new Map([['file', 'report.html']]),
json: false
})
expect(call).toHaveBeenCalledWith(
'artifacts.share',
expect.objectContaining({ content: '<h1>Hi</h1>' })
)
})
it.each(['environment', 'pairing-code'])(
'rejects explicit remote selector --%s',
async (flag) => {
const call = vi.fn()
await expect(
ARTIFACT_HANDLERS['artifacts list']!({
client: { call } as never,
cwd: '/repo',
flags: new Map([[flag, 'remote-host']]),
json: false
})
).rejects.toThrow(/does not retarget artifact commands/)
expect(call).not.toHaveBeenCalled()
}
)
})
+5 -5
View File
@@ -5,18 +5,18 @@ import type {
ArtifactListPage,
ArtifactListItem,
ArtifactWriteRequest
} from '../../shared/artifacts'
import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts'
} from '../../shared/artifacts/artifacts'
import { ARTIFACT_CLI_MAX_RPC_BYTES } from '../../shared/artifacts/artifacts'
import {
parseRemoteArtifactInput,
REMOTE_ARTIFACT_INPUT_ENV
} from '../../shared/artifact-cli-bridge'
import { readArtifactFileWithinLimit } from '../../shared/artifact-file-read'
} from '../../shared/artifacts/artifact-cli-bridge'
import { readArtifactFileWithinLimit } from '../../shared/artifacts/artifact-file-read'
import {
ARTIFACT_SHARING_DISABLED_CODE,
ARTIFACT_SHARING_DISABLED_MESSAGE,
ARTIFACT_SHARING_DISABLED_NEXT_STEPS
} from '../../shared/artifact-sharing-gate'
} from '../../shared/artifacts/artifact-sharing-gate'
import type { CommandHandler, HandlerContext } from '../dispatch'
import { rejectRemoteSelectionFlags } from '../remote-selection-flag-rejection'
import { RuntimeClientError } from '../runtime-client'
+1 -1
View File
@@ -1,4 +1,4 @@
import type { RuntimeFileOpenResult } from '../../shared/runtime-types'
import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open'
import type { HandlerContext } from '../dispatch'
import { RuntimeClientError, type RuntimeRpcSuccess } from '../runtime-client'
+1 -1
View File
@@ -1,4 +1,4 @@
import type { RuntimeFileOpenPosition } from '../../shared/runtime-file-contracts'
import type { RuntimeFileOpenPosition } from '../../shared/file-access/runtime-editor-file-open'
import { getOptionalPositiveIntegerFlag } from '../flags'
import { RuntimeClientError } from '../runtime-client'
+2 -1
View File
@@ -1,6 +1,7 @@
import { getFileOpenPosition } from './file-open-position'
import type { GitStatusEntry, GitStatusResult } from '../../shared/git/status/git-status-types'
import type { RuntimeFileOpenResult, RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeFileOpenResult } from '../../shared/file-access/runtime-editor-file-open'
import type { RuntimeWorktreeRecord } from '../../shared/runtime-types'
import type { RuntimeNavigationTarget } from '../../shared/runtime-navigation'
import { isRuntimePathAbsolute, relativePathInsideRoot } from '../../shared/cross-platform-path'
import { isWslUncPath, parseWslUncPath, toWindowsWslPath } from '../../shared/wsl-paths'
+2 -2
View File
@@ -11,12 +11,12 @@ import {
} from '../../shared/agent-session/failures/agent-session-failure-words'
import { formatNativeChatFileReference } from '../../shared/agent-image-paste'
import type { AgentJournalMessageItem } from '../../shared/agent-session/journal/agent-session-journal-types'
import { IMAGE_FILE_MIME_TYPES } from '../../shared/image-file-extensions'
import { IMAGE_FILE_MIME_TYPES } from '../../shared/file-preview/image-mime-types'
import type { NativeChatImageRefBlock } from '../../shared/native-chat/native-chat-types'
import {
NodeFileReadTooLargeError,
readNodeFileWithinLimit
} from '../../shared/node-bounded-file-reader'
} from '../../shared/file-content/node-bounded-file-reader'
import type { AcpLaunchSpec } from './acp-launch-specs'
import { resolveAcpPeerOptions } from './acp-peer-limits'
import { acpAgentName } from './acp-structured-agent-definitions'
@@ -15,7 +15,7 @@ import {
type ClaudeTrustConfigTarget,
grantClaudeWorkspaceTrust
} from '../../claude/claude-folder-trust-file'
import { isTooBroadToPreTrust } from '../../../shared/home-or-filesystem-root'
import { isTooBroadToPreTrust } from '../../../shared/agent-launch/permissions/workspace-pretrust-scope'
/** Resolve trust on the agent’s execution host, including WSL guests and SSH relays. */
export type WorkspaceTrustHost = {
@@ -1,10 +1,9 @@
import type * as NodeFsPromises from 'node:fs/promises'
import { constants } from 'node:fs'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { runProcess } from '@orca/process-host'
const { afterStat } = vi.hoisted(() => {
const afterStat: { run: null | (() => Promise<void>) } = { run: null }
@@ -21,7 +20,7 @@ vi.mock('node:fs/promises', async (original) => {
}
}
})
import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader'
import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader'
import { readLocalAntigravityHistory } from './session-scanner-antigravity-history'
const roots: string[] = []
@@ -30,36 +29,12 @@ async function filePath() {
roots.push(root)
return join(root, 'projects.json')
}
async function fifo(path: string) {
const result = await runProcess({ program: 'mkfifo', args: [path], timeoutMs: 2000 })
if (result.code !== 0) {
throw new Error('Could not create task-owned FIFO')
}
}
afterEach(async () => {
afterStat.run = null
await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true })))
})
describe('bounded regular metadata reads', () => {
it.skipIf(process.platform === 'win32')(
'rejects a regular path replaced by a FIFO between stat and open',
async () => {
const file = await filePath()
await writeFile(file, '{}')
afterStat.run = async () => {
afterStat.run = null
await rm(file)
await fifo(file)
}
await expect(readNodeFileWithinLimit(file, 64, { regularFileOnly: true })).rejects.toThrow(
'regular file'
)
expect(constants.O_NONBLOCK).toBeGreaterThan(0)
},
2000
)
it('retains ordinary metadata within the byte bound', async () => {
const file = await filePath()
await writeFile(file, '{"project":"/workspace"}')
@@ -9,7 +9,7 @@ import {
openTranscriptReadStream,
wslGatedStat
} from '../../../native-chat/wsl-transcript-fs-access'
import { readNodeFileWithinLimit } from '../../../../shared/node-bounded-file-reader'
import { readNodeFileWithinLimit } from '../../../../shared/file-content/node-bounded-file-reader'
import { isWslUncPath } from '../../../../shared/wsl-paths'
import { throwIfAiVaultScanCancelled } from '../../ai-vault-scan-cancellation'
import { WslTranscriptFsError } from '../../../native-chat/wsl-transcript-fs-error'
@@ -1,7 +1,7 @@
import { StringDecoder } from 'node:string_decoder'
import { FlexAssembler, arrayRule, objectRule } from 'stream-json/core/utils/flex-assembler.js'
import { setImmediate as yieldToEventLoop } from 'node:timers/promises'
import { createJsonTokenReader } from '../../../shared/json-token-reader'
import { createJsonTokenReader } from '../../../shared/json-stream/json-token-reader'
import { throwIfAiVaultScanCancelled } from '../ai-vault-scan-cancellation'
/** Fold one root array while retaining only the root fields the agent parser uses. */
+1 -1
View File
@@ -5,7 +5,7 @@ import { writeCredentialFileAtomic } from '../credentials/integration-credential
import type { AntigravityAccountSummary } from '../../shared/antigravity-account-types'
import type { ProviderRateLimits, RateLimitRuntimeTarget } from '../../shared/rate-limit-types'
import { parseAntigravityNativeCredential } from './native-credential-codec'
import { readPrivateWindowsFile } from '../../shared/secure-path-windows-acl'
import { readPrivateWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl'
export type StoredAntigravityUsage = {
target: RateLimitRuntimeTarget
@@ -1,7 +1,7 @@
import { existsSync, lstatSync, mkdirSync, readFileSync, statSync } from 'node:fs'
import { dirname } from 'node:path'
import { writeCredentialFileAtomic } from '../credentials/integration-credential-file'
import { readPrivateWindowsFile } from '../../shared/secure-path-windows-acl'
import { readPrivateWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl'
import { parseAntigravityNativeCredential } from './native-credential-codec'
import type { AntigravityCredentialBackend } from './native-account-service'
+1 -1
View File
@@ -1,4 +1,4 @@
import type { ArtifactWriteRequest } from '../../shared/artifacts'
import type { ArtifactWriteRequest } from '../../shared/artifacts/artifacts'
import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client'
export type ArtifactWriteBody = {
@@ -15,11 +15,7 @@ import {
unlinkOrcaProfileFromCloud
} from '../orca-profiles/profile-cloud-index'
import { signOutCloudSession } from '../orca-profiles/profile-cloud-session-owner'
import { saveOrcaCloudSession } from '../orca-profiles/profile-cloud-session-store'
import {
ARTIFACT_SHARING_DISABLED_CODE,
ARTIFACT_SHARING_DISABLED_MESSAGE
} from '../../shared/artifact-sharing-gate'
import { ArtifactCloudService } from './artifact-cloud-service'
const createdPaths: string[] = []
@@ -105,171 +101,6 @@ afterEach(async () => {
})
describe('ArtifactCloudService record authorization', () => {
it('serializes concurrent publishes for the same source', async () => {
const { service } = await setup()
let resolveCreate: ((response: Response) => void) | undefined
const fetchMock = vi
.fn()
.mockImplementationOnce(
() =>
new Promise<Response>((resolve) => {
resolveCreate = resolve
})
)
.mockResolvedValueOnce(createResponse())
vi.stubGlobal('fetch', fetchMock)
const first = service.publish(writeRequest)
const second = service.publish(writeRequest)
await vi.waitFor(() => expect(resolveCreate).toBeTypeOf('function'))
expect(fetchMock).toHaveBeenCalledOnce()
resolveCreate?.(createResponse())
await expect(Promise.all([first, second])).resolves.toMatchObject([
{ status: 'ok', value: { change: 'created' } },
{ status: 'ok', value: { change: 'updated' } }
])
expect(fetchMock).toHaveBeenCalledTimes(2)
expect(fetchMock.mock.calls[1]?.[1]).toMatchObject({ method: 'PUT' })
})
it('serializes manual publish with CLI share for the same source', async () => {
const { service } = await setup()
let resolvePublish: ((response: Response) => void) | undefined
const fetchMock = vi
.fn()
.mockImplementationOnce(
() =>
new Promise<Response>((resolve) => {
resolvePublish = resolve
})
)
.mockResolvedValueOnce(createResponse('artifact-b'))
vi.stubGlobal('fetch', fetchMock)
const publish = service.publish(writeRequest)
const share = service.share(writeRequest)
await vi.waitFor(() => expect(resolvePublish).toBeTypeOf('function'))
expect(fetchMock).toHaveBeenCalledOnce()
resolvePublish?.(createResponse('artifact-a'))
await expect(Promise.all([publish, share])).resolves.toMatchObject([
{ status: 'ok', value: { change: 'created' } },
{ status: 'ok', value: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } }
])
expect(fetchMock).toHaveBeenCalledTimes(2)
})
it('serializes account deletion with a mapped source update', async () => {
const { service } = await setup()
let resolveUpdate: ((response: Response) => void) | undefined
const fetchMock = vi
.fn()
.mockResolvedValueOnce(createResponse())
.mockImplementationOnce(
() =>
new Promise<Response>((resolve) => {
resolveUpdate = resolve
})
)
.mockResolvedValueOnce(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)
await service.share(writeRequest)
const update = service.update(writeRequest)
await vi.waitFor(() => expect(resolveUpdate).toBeTypeOf('function'))
const deletion = service.delete('artifact-a', { apiUrl, authToken: 'token-a' })
expect(fetchMock).toHaveBeenCalledTimes(2)
resolveUpdate?.(createResponse())
await expect(Promise.all([update, deletion])).resolves.toMatchObject([
{ status: 'ok' },
{ status: 'ok' }
])
await expect(
service.getPublishedLink({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' })
).resolves.toEqual({ status: 'ok', value: null })
expect(fetchMock).toHaveBeenCalledTimes(3)
})
it('recreates an artifact when its stored public link was deleted elsewhere', async () => {
const { service } = await setup()
const fetchMock = vi
.fn()
.mockResolvedValueOnce(createResponse('artifact-a'))
.mockResolvedValueOnce(new Response(JSON.stringify({ code: 'not_found' }), { status: 404 }))
.mockResolvedValueOnce(createResponse('artifact-b'))
.mockResolvedValueOnce(createResponse('artifact-b'))
vi.stubGlobal('fetch', fetchMock)
await service.publish(writeRequest)
await expect(service.publish(writeRequest)).resolves.toMatchObject({
status: 'ok',
value: { change: 'created', item: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } }
})
await expect(service.publish(writeRequest)).resolves.toMatchObject({
status: 'ok',
value: { change: 'updated', item: { shareUrl: 'https://share.onorca.dev/a/artifact-b' } }
})
expect(fetchMock.mock.calls.map(([, options]) => options?.method)).toEqual([
'POST',
'PUT',
'POST',
'PUT'
])
})
it('keeps the idempotency key stable across an auth-refresh retry', async () => {
const { service, profileId, userDataPath } = await setup()
vi.stubEnv('ORCA_CLOUD_API_URL', 'http://localhost:4100')
vi.stubEnv('ORCA_CLOUD_CLIENT_ID', 'desktop-client')
saveOrcaCloudSession(profileId, userDataPath, {
accessToken: 'access-old',
refreshToken: 'refresh-old',
expiresAt: Date.now() + 120_000,
capabilities: { flags: {}, refreshedAt: Date.now() }
})
let artifactAttempts = 0
const fetchMock = vi.fn().mockImplementation((input: string | URL) => {
const url = String(input)
if (url === `${apiUrl}/v1/artifacts`) {
artifactAttempts += 1
return Promise.resolve(
artifactAttempts === 1
? new Response(JSON.stringify({ code: 'invalid_access_token' }), { status: 401 })
: createResponse()
)
}
if (url === 'http://localhost:4100/v1/desktop/auth/refresh') {
return Promise.resolve(
new Response(
JSON.stringify({
accessToken: 'access-new',
refreshToken: 'refresh-new',
expiresAt: Date.now() + 3_600_000,
cloud: cloudA,
capabilities: { flags: {}, refreshedAt: Date.now() }
}),
{ status: 200, headers: { 'content-type': 'application/json' } }
)
)
}
throw new Error(`Unexpected URL: ${url}`)
})
vi.stubGlobal('fetch', fetchMock)
await expect(service.share({ ...writeRequest, authToken: undefined })).resolves.toMatchObject({
status: 'ok'
})
expect(requestHeader(fetchMock, 0, 'authorization')).toBe('Bearer access-old')
expect(requestHeader(fetchMock, 2, 'authorization')).toBe('Bearer access-new')
expect(requestHeader(fetchMock, 0, 'idempotency-key')).toBe(
requestHeader(fetchMock, 2, 'idempotency-key')
)
})
it('refuses account B update and unshare after account A signs out', async () => {
const { userDataPath, profileId, service } = await setup()
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(createResponse()))
@@ -337,77 +168,9 @@ describe('ArtifactCloudService record authorization', () => {
await expect(pending).resolves.toMatchObject({ status: 'ok' })
})
it('never scopes an explicit token to the profile linked in the UI', async () => {
const { service } = await setup()
const fetchMock = vi.fn().mockResolvedValue(createResponse())
vi.stubGlobal('fetch', fetchMock)
await service.share(writeRequest)
await expect(service.update({ ...writeRequest, authToken: 'token-b' })).rejects.toThrow(
/has not been shared/
)
expect(fetchMock).toHaveBeenCalledOnce()
})
it('keeps update and unshare working after an update extends expiration', async () => {
vi.useFakeTimers({ toFake: ['Date'] })
vi.setSystemTime('2026-08-07T00:00:00.000Z')
const { service } = await setup()
let resolveUpdate: ((response: Response) => void) | undefined
const fetchMock = vi
.fn()
.mockResolvedValueOnce(createResponse('artifact-a', '2026-09-06T00:00:00.000Z'))
.mockImplementationOnce(
() =>
new Promise<Response>((resolve) => {
resolveUpdate = resolve
})
)
.mockResolvedValueOnce(new Response(null, { status: 204 }))
vi.stubGlobal('fetch', fetchMock)
await service.share(writeRequest)
vi.setSystemTime('2026-09-05T00:00:00.000Z')
const update = service.update(writeRequest)
await vi.waitFor(() => expect(resolveUpdate).toBeTypeOf('function'))
vi.setSystemTime('2026-09-07T00:00:00.000Z')
resolveUpdate?.(createResponse('artifact-a', '2026-10-06T00:00:00.000Z'))
await update
await expect(
service.unshare({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' })
).resolves.toEqual({ status: 'ok', value: undefined })
expect(fetchMock).toHaveBeenCalledTimes(3)
})
})
describe('ArtifactCloudService publish capability gate', () => {
it.each([
['share', (service: ArtifactCloudService) => service.share(writeRequest)],
['publish', (service: ArtifactCloudService) => service.publish(writeRequest)],
['update', (service: ArtifactCloudService) => service.update(writeRequest)]
])('rejects %s without reaching the network when the capability is off', async (_name, call) => {
const { service } = await setup({ value: false })
const fetchMock = vi.fn().mockResolvedValue(createResponse())
vi.stubGlobal('fetch', fetchMock)
await expect(call(service)).rejects.toMatchObject({
code: ARTIFACT_SHARING_DISABLED_CODE,
data: { nextSteps: expect.arrayContaining([expect.stringContaining('Settings')]) }
})
expect(fetchMock).not.toHaveBeenCalled()
})
it('persists no share record for a denied share, so a later update stays denied', async () => {
const sharing = { value: false }
const { service } = await setup(sharing)
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(createResponse()))
await expect(service.share(writeRequest)).rejects.toThrow(ARTIFACT_SHARING_DISABLED_MESSAGE)
sharing.value = true
await expect(service.update(writeRequest)).rejects.toThrow(/has not been shared/)
})
it('keeps list and unshare working so links stay revocable after opting out', async () => {
const sharing = { value: true }
const { service } = await setup(sharing)
@@ -438,27 +201,4 @@ describe('ArtifactCloudService publish capability gate', () => {
service.unshare({ sourceKey: writeRequest.sourceKey, apiUrl, authToken: 'token-a' })
).resolves.toEqual({ status: 'ok', value: undefined })
})
it('re-reads the capability per call so revoking it stops the next share', async () => {
const sharing = { value: true }
const { service } = await setup(sharing)
const fetchMock = vi.fn().mockResolvedValue(createResponse())
vi.stubGlobal('fetch', fetchMock)
await service.share(writeRequest)
sharing.value = false
await expect(service.share({ ...writeRequest, sourceKey: '/repo/other.html' })).rejects.toThrow(
ARTIFACT_SHARING_DISABLED_MESSAGE
)
expect(fetchMock).toHaveBeenCalledOnce()
})
})
function requestHeader(
fetchMock: ReturnType<typeof vi.fn>,
index: number,
name: string
): string | null {
const init = fetchMock.mock.calls[index]?.[1] as RequestInit | undefined
return new Headers(init?.headers).get(name)
}
+2 -2
View File
@@ -8,8 +8,8 @@ import type {
ArtifactPublishedLink,
ArtifactPublishResult,
ArtifactWriteRequest
} from '../../shared/artifacts'
import { assertArtifactSharingAllowed } from '../../shared/artifact-sharing-gate'
} from '../../shared/artifacts/artifacts'
import { assertArtifactSharingAllowed } from '../../shared/artifacts/artifact-sharing-gate'
import { ensureActiveOrcaProfile } from '../orca-profiles/profile-index-store'
import { getOrcaCloudAuthConfig } from '../orca-profiles/profile-cloud-auth-config'
import { prepareArtifactCloudUse } from '../orca-profiles/profile-artifact-cloud-cleanup'
@@ -1,12 +1,8 @@
import { mkdtemp, readFile, readdir, rm, stat, truncate, writeFile } from 'node:fs/promises'
import { mkdtemp, readFile, readdir, rm, truncate, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
ARTIFACT_MAX_CONTENT_BYTES,
ARTIFACT_MAX_REQUEST_BYTES,
artifactWriteRequestByteLength
} from '../../shared/artifacts'
import { ARTIFACT_MAX_CONTENT_BYTES } from '../../shared/artifacts/artifacts'
import {
MAX_ARTIFACT_CREATE_INTENT_BYTES,
MAX_PENDING_ARTIFACT_CREATES,
@@ -238,31 +234,6 @@ describe('artifact create intent store', () => {
).toThrow(/unsupported format/)
})
it('persists an escaped artifact within the recovery limit', async () => {
const userDataPath = await createUserDataPath()
const nearLimitBody = {
...body,
content: '"'.repeat(Math.floor(ARTIFACT_MAX_CONTENT_BYTES / 2))
}
expect(
artifactWriteRequestByteLength({ sourceKey: '/repo/report.html', ...nearLimitBody })
).toBeLessThanOrEqual(ARTIFACT_MAX_REQUEST_BYTES)
expect(() =>
getOrCreateArtifactCreateIntent(
'local-profile',
userDataPath,
'/repo/report.html',
scope,
'key-a',
nearLimitBody
)
).not.toThrow()
const directory = join(userDataPath, 'profiles', 'local-profile', 'artifact-create-intents')
const [fileName] = await readdir(directory)
expect((await stat(join(directory, fileName))).size).toBeGreaterThan(ARTIFACT_MAX_CONTENT_BYTES)
})
it('rejects oversized artifact content before creating a recovery record', async () => {
const userDataPath = await createUserDataPath()
expect(() =>
@@ -277,26 +248,6 @@ describe('artifact create intent store', () => {
).toThrow(/10 MiB limit/)
})
it('rejects a recovery body whose escaped request exceeds the transport budget', async () => {
const userDataPath = await createUserDataPath()
const content = '\u0000'.repeat(Math.ceil(ARTIFACT_MAX_REQUEST_BYTES / 6))
expect(content.length).toBeLessThan(ARTIFACT_MAX_CONTENT_BYTES)
expect(
artifactWriteRequestByteLength({ sourceKey: '/repo/report.html', ...body, content })
).toBeGreaterThan(ARTIFACT_MAX_REQUEST_BYTES)
expect(() =>
getOrCreateArtifactCreateIntent(
'local-profile',
userDataPath,
'/repo/report.html',
scope,
'key-a',
{ ...body, content }
)
).toThrow(/supported size/)
})
it('rejects an oversized recovery record before reading it', async () => {
const userDataPath = await createUserDataPath()
const directory = join(userDataPath, 'profiles', 'local-profile', 'artifact-create-intents')
@@ -6,8 +6,11 @@ import {
ARTIFACT_MAX_REQUEST_BYTES,
artifactContentByteLength,
artifactWriteRequestByteLength
} from '../../shared/artifacts'
import { bestEffortFsyncDirectorySync, writeSecureFile } from '../../shared/secure-file'
} from '../../shared/artifacts/artifacts'
import {
bestEffortFsyncDirectorySync,
writeSecureFile
} from '../../shared/secure-storage/secure-file'
import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths'
import type { ArtifactWriteBody } from './artifact-cloud-request'
import type { ArtifactShareScope } from './artifact-share-record-store'
+1 -1
View File
@@ -2,7 +2,7 @@ import type {
ArtifactListItem,
ArtifactPublishResult,
ArtifactWriteRequest
} from '../../shared/artifacts'
} from '../../shared/artifacts/artifacts'
import { OrcaCloudRequestError } from '../orca-profiles/profile-cloud-client'
import {
artifactRequest,
@@ -33,7 +33,10 @@ vi.mock('node:fs', async () => {
}
})
import { bestEffortFsyncDirectorySync, writeDurableSecureJsonFile } from '../../shared/secure-file'
import {
bestEffortFsyncDirectorySync,
writeDurableSecureJsonFile
} from '../../shared/secure-storage/secure-file'
import {
clearArtifactCreateIntents,
getOrCreateArtifactCreateIntent
@@ -1,7 +1,10 @@
import { randomUUID } from 'node:crypto'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { writeDurableSecureJsonFile, writeSecureJsonFile } from '../../shared/secure-file'
import {
writeDurableSecureJsonFile,
writeSecureJsonFile
} from '../../shared/secure-storage/secure-file'
import { getOrcaProfileDirectory } from '../orca-profiles/profile-storage-paths'
export type ArtifactShareScope = {
+3 -33
View File
@@ -2,7 +2,7 @@ import { existsSync, mkdtempSync, readdirSync, statSync } from 'node:fs'
import type * as Fs from 'node:fs'
import { tmpdir } from 'node:os'
import type * as Os from 'node:os'
import type * as WindowsAcl from '../../shared/secure-path-windows-acl'
import type * as WindowsAcl from '../../shared/secure-storage/secure-path-windows-acl'
import { join } from 'node:path'
import { beforeEach, describe, expect, it, vi } from 'vitest'
@@ -19,7 +19,7 @@ async function loadStore(
vi.resetModules()
// resetModules leaves doMock registrations behind.
vi.doUnmock('node:fs')
vi.doUnmock('../../shared/secure-path-windows-acl')
vi.doUnmock('../../shared/secure-storage/secure-path-windows-acl')
const { setSecretStore } = await import('../../shared/secret-store')
setSecretStore({
isEncryptionAvailable: () => true,
@@ -53,7 +53,7 @@ async function loadStore(
}
})
// Windows writes use the ACL helper.
vi.doMock('../../shared/secure-path-windows-acl', async (importOriginal) => ({
vi.doMock('../../shared/secure-storage/secure-path-windows-acl', async (importOriginal) => ({
...(await importOriginal<typeof WindowsAcl>()),
writeRestrictedWindowsFile: () => {
throw error
@@ -105,36 +105,6 @@ describe('Bitbucket credential store', () => {
}
})
it('does not decrypt for metadata/status reads — only on a forced secret load', async () => {
const store = await loadStore()
store.saveBitbucketCredential({
authMode: 'token',
email: null,
baseUrl: 'https://api.bitbucket.org/2.0',
account: 'dev',
accessToken: 'access-secret',
apiToken: null
})
store._resetBitbucketCredentialCache()
expect(store.getStoredBitbucketMetadata()?.account).toBe('dev')
expect(store.hasStoredBitbucketCredential()).toBe(true)
expect(decryptStringMock).not.toHaveBeenCalled()
expect(store.loadStoredBitbucketSecret()).toBeNull()
expect(decryptStringMock).not.toHaveBeenCalled()
expect(store.loadStoredBitbucketSecret({ force: true })).toMatchObject({
accessToken: 'access-secret',
apiToken: null,
authMode: 'token'
})
expect(decryptStringMock).toHaveBeenCalledTimes(1)
expect(store.loadStoredBitbucketSecret()).not.toBeNull()
expect(decryptStringMock).toHaveBeenCalledTimes(1)
})
it('rejects non-string fields from hand-edited metadata and secret files', async () => {
const store = await loadStore()
const { writeFileSync } = await import('node:fs')
@@ -1,7 +1,7 @@
import { readFileSync, rmSync } from 'node:fs'
import type { BrowserPasswordEntrySummary } from '../../shared/browser-passwords-types'
import { getSecretStore, hasSecretStore } from '../../shared/secret-store'
import { writeSecureFile } from '../../shared/secure-file'
import { writeSecureFile } from '../../shared/secure-storage/secure-file'
/**
* On-disk vault: usernames and sites sit in one sealed index; each password is sealed on its own
@@ -15,7 +15,7 @@ import {
agentBrowserScreenshotArgs,
readAgentBrowserScreenshot
} from './agent-browser-screenshot-arguments'
import { readRasterImageDimensions } from '../../../shared/raster-image-dimensions'
import { readRasterImageDimensions } from '../../../shared/file-preview/raster-image-dimensions'
import { acquireElectronDebugger } from '../cdp/debugger/electron-debugger-lease'
import { sendGuestCdpCommand } from '../cdp/debugger/guest-cdp-command'
import { AgentBrowserBridgeUtilityCommands } from './agent-browser-bridge-page-commands'
@@ -1,7 +1,7 @@
import {
DOC_PREVIEW_LOAD_FAILURE_CHANNEL,
type DocPreviewFailure
} from '../../../shared/doc-preview-scheme'
} from '../../../shared/document-preview/doc-preview-scheme'
type DocPreviewFailureSink = {
send: (channel: string, payload: DocPreviewFailure) => void
@@ -1,12 +1,12 @@
import { extname } from 'node:path'
import type { RuntimeFilePreviewResult } from '../../../shared/runtime-file-contracts'
import type { DocPreviewFileFailureReason } from '../../../shared/doc-preview-scheme'
import { FONT_FILE_MIME_TYPES } from '../../../shared/font-file-extensions'
import { isBinaryBuffer } from '../../../shared/binary-buffer'
import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read'
import type { DocPreviewFileFailureReason } from '../../../shared/document-preview/doc-preview-scheme'
import { FONT_FILE_MIME_TYPES } from '../../../shared/file-preview/font-file-extensions'
import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer'
import {
DOC_PREVIEW_FILE_CHANGED_MESSAGE,
type DocPreviewFileChunk
} from '../../../shared/doc-preview-file-access'
} from '../../../shared/document-preview/doc-preview-file-access'
import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing'
import { SSH_HOST_NOT_SERVED_MESSAGE } from '../../providers/ssh-host-not-served-error'
import {
@@ -1,7 +1,7 @@
import { randomBytes } from 'node:crypto'
import { posix, win32 } from 'node:path'
import { isWindowsAbsolutePathLike } from '../../../shared/cross-platform-path'
import { parseDocPreviewUrl } from '../../../shared/doc-preview-scheme'
import { parseDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme'
export type DocPreviewOwner =
| { kind: 'ssh'; connectionId: string }
@@ -4,7 +4,7 @@ import {
installDocPreviewGuestPolicy,
readDocPreviewGuestDocumentUrl
} from './doc-preview-guest-policy'
import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme'
import { buildDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme'
import { mintDocPreviewGrant, revokeAllDocPreviewGrants } from './doc-preview-grant-registry'
type GuestHandlers = Record<string, (...args: unknown[]) => void>
@@ -2,7 +2,7 @@ import {
DOC_PREVIEW_EXTERNAL_LINK_CHANNEL,
parseDocPreviewUrl,
type DocPreviewExternalLink
} from '../../../shared/doc-preview-scheme'
} from '../../../shared/document-preview/doc-preview-scheme'
import { normalizeExternalBrowserUrl } from '../../../shared/browser-url'
import { enforceBrowserRouteWebRtcPolicy } from '../network/egress/browser-route-webrtc-policy'
import { getDocPreviewGrant } from './doc-preview-grant-registry'
@@ -3,7 +3,7 @@ import {
DOC_PREVIEW_PARTITION,
DOC_PREVIEW_SCHEME,
parseDocPreviewUrl
} from '../../../shared/doc-preview-scheme'
} from '../../../shared/document-preview/doc-preview-scheme'
import { installBrowserSessionPartitionPolicies } from '../sessions/browser-session-partition-policies'
import { readDocPreviewFile } from './doc-preview-file-reader'
import { publishDocPreviewFailure } from './doc-preview-failure-notice'
@@ -1,83 +0,0 @@
import { Buffer } from 'node:buffer'
import { createHash } from 'node:crypto'
import { types } from 'node:util'
import { runInNewContext } from 'node:vm'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({ readDocPreviewFile: vi.fn() }))
vi.mock('electron', () => ({ protocol: {}, session: {} }))
vi.mock('./doc-preview-file-reader', () => ({ readDocPreviewFile: mocks.readDocPreviewFile }))
vi.mock('../sessions/browser-session-partition-policies', () => ({
installBrowserSessionPartitionPolicies: vi.fn()
}))
import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme'
import { setDocPreviewFailureSink } from './doc-preview-failure-notice'
import { mintDocPreviewGrant, revokeAllDocPreviewGrants } from './doc-preview-grant-registry'
import { handleDocPreviewRequest } from './doc-preview-protocol'
function digest(bytes: Uint8Array): string {
return createHash('sha256').update(bytes).digest('hex')
}
async function serve(bytes: Buffer, contentType = 'text/html; charset=utf-8'): Promise<Response> {
const grant = mintDocPreviewGrant({
owner: { kind: 'ssh', connectionId: 'ssh-1' },
root: '/home/alice/docs',
entryRelativePath: 'index.html',
browserPageId: 'page-1'
})
mocks.readDocPreviewFile.mockResolvedValueOnce({ ok: true, bytes, contentType })
return handleDocPreviewRequest(new Request(buildDocPreviewUrl(grant.id, 'index.html')))
}
beforeEach(() => {
vi.clearAllMocks()
revokeAllDocPreviewGrants()
setDocPreviewFailureSink(null)
})
afterEach(() => {
revokeAllDocPreviewGrants()
})
describe('document preview response allocation', () => {
it('keeps only the requested range and snapshots pooled, offset, shared and cross-realm bytes', async () => {
const payload = Buffer.from('<p>π😀\u0000 independent bytes</p>', 'utf8')
const expectedDigest = digest(payload)
const pooled = Buffer.from(payload)
expect(pooled.buffer.byteLength).toBeGreaterThan(pooled.byteLength)
const backing = new ArrayBuffer(payload.byteLength + 4096)
new Uint8Array(backing).fill(0xa5)
const offset = Buffer.from(backing, 127, payload.byteLength)
offset.set(payload)
expect(offset.byteOffset).toBe(127)
const sharedBacking = new SharedArrayBuffer(payload.byteLength + 4096)
const shared = Buffer.from(sharedBacking, 127, payload.byteLength)
shared.set(payload)
const foreignBacking: unknown = runInNewContext('new ArrayBuffer(4096)')
if (!types.isAnyArrayBuffer(foreignBacking)) {
throw new Error('Expected a cross-realm byte backing')
}
expect(foreignBacking instanceof ArrayBuffer).toBe(false)
const foreign = Buffer.from(foreignBacking, 127, payload.byteLength)
foreign.set(payload)
for (const source of [pooled, offset, shared, foreign]) {
const response = await serve(source)
source.fill(0x7f)
const clone = response.clone()
for (const body of [response, clone]) {
const bytes = Buffer.from(await body.arrayBuffer())
expect(bytes.byteLength).toBe(payload.byteLength)
expect(digest(bytes)).toBe(expectedDigest)
expect(body.bodyUsed).toBe(true)
await expect(body.arrayBuffer()).rejects.toThrow()
expect(() => body.clone()).toThrow()
}
}
})
})
@@ -1,4 +1,4 @@
import type { RuntimeFilePreviewResult } from '../../../shared/runtime-file-contracts'
import type { RuntimeFilePreviewResult } from '../../../shared/file-content/runtime-file-read'
import { callRuntimeEnvironment } from '../../ipc/runtime-environments/runtime-environment-transport-routing'
import { getRuntimeEnvironmentRegistryRoot } from '../../ipc/runtime-environments/runtime-environment-registry-root'
import {
@@ -4,7 +4,7 @@ import {
mintDocPreviewGrant,
revokeDocPreviewGrant
} from '../document-preview/doc-preview-grant-registry'
import { buildDocPreviewUrl } from '../../../shared/doc-preview-scheme'
import { buildDocPreviewUrl } from '../../../shared/document-preview/doc-preview-scheme'
function makeRawPayload(overrides: Record<string, unknown> = {}) {
return {
@@ -1,6 +1,6 @@
import { app, shell } from 'electron'
import { DOC_PREVIEW_SCHEME } from '../../../../shared/doc-preview-scheme'
import { DOC_PREVIEW_SCHEME } from '../../../../shared/document-preview/doc-preview-scheme'
import { BROWSER_EXTENSION_API_SCHEME } from '../../../../shared/browser/extensions/browser-extension-worker-api'
import {
browserPagePromptOrigin,
+1 -1
View File
@@ -1,4 +1,4 @@
import { assertJsonTextStructureWithinLimits } from '../../shared/json-text-structure-limit'
import { assertJsonTextStructureWithinLimits } from '../../shared/json-stream/json-text-structure-limit'
const CONTROL_JSON_LIMITS = { structuralTokens: 64 * 1024, nestingDepth: 16 } as const
+1 -1
View File
@@ -3,7 +3,7 @@ import { existsSync, linkSync, rmSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import { grantDirAcl } from '../windows/windows-directory-acl'
import { isPermissionError } from '../filesystem/permission-errors'
import { nodeFileContentsEqualSync } from '../../shared/node-file-content-equality'
import { nodeFileContentsEqualSync } from '../../shared/file-content/node-file-content-equality'
import {
copyFileWithWindowsRetry,
renameFileWithWindowsRetry,
@@ -2,7 +2,7 @@ import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { NodeFileReadTooLargeError } from '../../../shared/node-bounded-file-reader'
import { NodeFileReadTooLargeError } from '../../../shared/file-content/node-bounded-file-reader'
import {
MAX_AGENT_STATE_FILE_BYTES,
MAX_AGENT_STATE_JSON_NESTING_DEPTH,
@@ -34,17 +34,6 @@ describe('readAgentStateFileSync', () => {
expect(readAgentStateFileSync(filePath)).toBe(contents)
})
it('reads a sparse file at the exact 4 MiB boundary', () => {
const filePath = tempFile('snapshot.json')
writeFileSync(filePath, '')
truncateSync(filePath, MAX_AGENT_STATE_FILE_BYTES)
const contents = readAgentStateFileSync(filePath)
expect(contents).toHaveLength(MAX_AGENT_STATE_FILE_BYTES)
expect(contents.charCodeAt(MAX_AGENT_STATE_FILE_BYTES - 1)).toBe(0)
})
it('rejects a sparse file one byte over the boundary before reading its payload', () => {
const filePath = tempFile('oversized.json')
writeFileSync(filePath, '')
@@ -1,5 +1,5 @@
import { readNodeFileSyncWithinLimit } from '../../../shared/node-bounded-file-reader'
import { assertJsonTextStructureWithinLimits } from '../../../shared/json-text-structure-limit'
import { readNodeFileSyncWithinLimit } from '../../../shared/file-content/node-bounded-file-reader'
import { assertJsonTextStructureWithinLimits } from '../../../shared/json-stream/json-text-structure-limit'
export const MAX_AGENT_STATE_FILE_BYTES = 4 * 1024 * 1024
export const MAX_AGENT_STATE_JSON_STRUCTURAL_TOKENS = 1_000_000
@@ -1,7 +1,7 @@
import { writeFileSync } from 'node:fs'
import { isDefinitiveAbsence } from '../../../../shared/definitive-filesystem-absence'
import { JsonTextStructureCapacityError } from '../../../../shared/json-text-structure-limit'
import { NodeFileReadTooLargeError } from '../../../../shared/node-bounded-file-reader'
import { JsonTextStructureCapacityError } from '../../../../shared/json-stream/json-text-structure-limit'
import { NodeFileReadTooLargeError } from '../../../../shared/file-content/node-bounded-file-reader'
import { join } from 'node:path'
import { readAgentStateFileSync, readAgentStateJsonFileSync } from '../agent-state-file-reader'
@@ -1,6 +1,6 @@
import type { AgentJournalMessageItem } from '../../../../shared/agent-session/journal/agent-session-journal-types'
import type { NativeChatBlock } from '../../../../shared/native-chat/native-chat-types'
import { buildImageDataUri } from '../../../../shared/image-data-uri'
import { buildImageDataUri } from '../../../../shared/file-preview/image-data-uri'
import { readString } from '../../app-server/codex-item-field-readers'
import type { CodexThreadItem } from './codex-thread-item-identity'
@@ -8,7 +8,7 @@ import {
ConnectorConversation,
type ConnectorEvent
} from '../../shared/connector-cloud-contract'
import { writeSecureJsonFile } from '../../shared/secure-file'
import { writeSecureJsonFile } from '../../shared/secure-storage/secure-file'
import type {
ConversationEvent,
ConversationSnapshot
@@ -6,7 +6,7 @@ import {
hardenExistingSecureFile,
isUnreadableError,
writeSecureFile
} from '../../shared/secure-file'
} from '../../shared/secure-storage/secure-file'
import type { SecretAtRestProtection } from '../../shared/secret-at-rest-protection'
import { ApiKeyFileUnreadableError } from './api-key-file-unreadable-error'
@@ -10,8 +10,8 @@ import {
writeSync
} from 'node:fs'
import { getSecretStore } from '../../shared/secret-store'
import { fsyncFileSync } from '../../shared/secure-file'
import { writeRestrictedWindowsFile } from '../../shared/secure-path-windows-acl'
import { fsyncFileSync } from '../../shared/secure-storage/secure-file'
import { writeRestrictedWindowsFile } from '../../shared/secure-storage/secure-path-windows-acl'
import {
credentialDecryptionMessage,
type IntegrationCredentialService
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from 'node:crypto'
import { lstat, mkdir, rm, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader'
import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader'
import { renameFileWithWindowsRetryAsync } from '../../../shared/windows-retry-file-operations'
import {
isConfiguredTerminalLimit,
@@ -1,5 +1,5 @@
import { runProcess } from '@orca/process-host'
import { readNodeFileWithinLimit } from '../../../shared/node-bounded-file-reader'
import { readNodeFileWithinLimit } from '../../../shared/file-content/node-bounded-file-reader'
import { InFlightPromiseDedupe } from '../../../shared/in-flight-promise-dedupe'
import { awaitDaemonValueWithinCallerDeadline } from '../launch/daemon-request-deadline'
@@ -1,7 +1,7 @@
import {
readNodeFileSyncWithinLimit,
readNodeFileWithinLimit
} from '../../../../shared/node-bounded-file-reader'
} from '../../../../shared/file-content/node-bounded-file-reader'
export function readTerminalHistoryBuffer(filePath: string, maxBytes: number): Buffer {
return readNodeFileSyncWithinLimit(filePath, maxBytes).buffer
@@ -1,6 +1,6 @@
import { realpath, rename } from 'node:fs/promises'
import { dirname, normalize } from 'node:path'
import { assertNoClobberRenameDestinationAvailable } from '../../shared/filesystem-rename-collision'
import { assertNoClobberRenameDestinationAvailable } from '../../shared/file-write/filesystem-rename-collision'
import { windowsFsPath } from '../wsl/filesystem/wsl-unc-drive-fs-path'
// Parent-scoped serialization covers Unicode aliases without guessing filesystem collation.
+1 -1
View File
@@ -3,7 +3,7 @@ import { getLargeDiffRenderLimit } from '../../../shared/large-diff-render-limit
import {
IMAGE_AND_PDF_PREVIEW_MIME_TYPES,
filePreviewExtension
} from '../../../shared/file-preview-kind'
} from '../../../shared/file-preview/file-preview-kind'
export function buildDiffResult(
originalContent: string,
+1 -1
View File
@@ -1,5 +1,5 @@
import { readFile, stat } from 'node:fs/promises'
import { isBinaryBuffer } from '../../../shared/binary-buffer'
import { isBinaryBuffer } from '../../../shared/file-preview/binary-buffer'
import { isMissingGitBlobPath } from '../../../shared/git/diff/git-blob-absence'
import { readGitCommandFailureStderr } from '../../../shared/git/commands/git-command-failure-text'
import type { GitRuntimeOptions } from '../git-runtime-options'
@@ -1,184 +0,0 @@
import type * as RunnerModule from '../runner'
import type * as GitExecFileModule from '../command-runner/git-exec-file'
import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout'
import type * as GitProcessEnvModule from '../command-runner/git-process-env'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import {
createBoundedFileReaderModuleMock,
createFsPromisesModuleMock,
createGitRunnerModuleMock
} from './status-test-harness'
const {
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock,
lstatMock,
realpathMock,
readFileMock,
statMock,
rmMock,
existsSyncMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileAsyncBufferMock: vi.fn(),
gitStreamOptionsMock: vi.fn(),
lstatMock: vi.fn(),
realpathMock: vi.fn(),
readFileMock: vi.fn(),
statMock: vi.fn(),
rmMock: vi.fn(),
existsSyncMock: vi.fn()
}))
vi.mock('../runner', () =>
createGitRunnerModuleMock({
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock
})
)
vi.mock('../command-runner/git-exec-file', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitExecFileModule>()),
gitExecFileAsync: runnerMocks.gitExecFileAsync,
gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer
}
})
vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitStreamStdoutModule>()),
gitStreamStdout: runnerMocks.gitStreamStdout
}
})
vi.mock('../command-runner/git-process-env', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitProcessEnvModule>()),
gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv
}
})
vi.mock('fs/promises', () =>
createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock })
)
vi.mock('fs', () => ({
existsSync: existsSyncMock
}))
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) =>
createBoundedFileReaderModuleMock(await importOriginal<typeof BoundedFileReader>(), {
readFileMock,
statMock
})
)
import { getBranchCompare } from './branch-compare'
describe('getBranchCompare', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileAsyncBufferMock.mockReset()
readFileMock.mockReset()
})
// Route by argv so independent concurrent reads can reorder safely.
type BranchCompareGitResponses = {
branch?: string | Error
probe?: Record<string, string | Error>
headOid?: string | Error
baseOid?: string | Error
mergeBase?: string | Error
onMergeBase?: () => void
nameStatus?: string | Error
numstat?: string | Error
revList?: string | Error
}
function mockBranchCompareGit(responses: BranchCompareGitResponses): void {
const reply = (
value: string | Error | undefined,
label: string
): Promise<{ stdout: string }> => {
if (value === undefined) {
throw new Error(`unexpected git call: ${label}`)
}
return value instanceof Error ? Promise.reject(value) : Promise.resolve({ stdout: value })
}
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args[0] === 'branch') {
return reply(responses.branch, 'branch --show-current')
}
if (args[0] === 'rev-parse' && args.includes('--quiet')) {
const probed = args.find((arg) => arg.endsWith('^{commit}')) ?? ''
return reply(responses.probe?.[probed], `probe ${probed}`)
}
if (args[0] === 'rev-parse' && args.includes('HEAD')) {
return reply(responses.headOid, 'rev-parse HEAD')
}
if (args[0] === 'rev-parse') {
return reply(responses.baseOid, `rev-parse ${args.at(-1)}`)
}
if (args[0] === 'merge-base') {
responses.onMergeBase?.()
return reply(responses.mergeBase, 'merge-base')
}
if (args.includes('--raw')) {
const raw =
typeof responses.nameStatus === 'string'
? responses.nameStatus
.split(/\r?\n/)
.filter(Boolean)
.map((line) => {
const [status, ...paths] = line.split('\t')
return `:100644 100644 a b ${status}\0${paths.join('\0')}\0`
})
.join('')
: responses.nameStatus
if (raw instanceof Error) {
return reply(raw, 'diff')
}
if (responses.numstat instanceof Error) {
return reply(responses.numstat, 'diff')
}
return reply((raw ?? '') + (responses.numstat ?? ''), 'diff')
}
if (args[0] === 'rev-list') {
return reply(responses.revList, 'rev-list')
}
throw new Error(`unexpected git args: ${args.join(' ')}`)
})
}
it('keeps cancellation effective when equal-tip validation settles', async () => {
const oid = 'a'.repeat(40)
const controller = new AbortController()
mockBranchCompareGit({
branch: 'feature\n',
probe: { 'refs/remotes/origin/main^{commit}': `${oid}\n` },
headOid: `${oid}\n`,
baseOid: `${oid}\n`,
mergeBase: `${oid}\n`,
onMergeBase: () => controller.abort(new Error('compare canceled'))
})
await expect(
getBranchCompare('/repo', 'origin/main', { signal: controller.signal })
).resolves.toMatchObject({
summary: { status: 'error', errorMessage: 'compare canceled' },
entries: []
})
expect(
gitExecFileAsyncMock.mock.calls.some(([args]) => ['diff', 'rev-list'].includes(args[0]))
).toBe(false)
})
// Keep distinct probe results to catch accidental reuse of the losing ref's OID.
})
@@ -3,9 +3,9 @@ import type * as GitExecFileModule from '../command-runner/git-exec-file'
import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout'
import type * as GitProcessEnvModule from '../command-runner/git-process-env'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader'
import path from 'node:path'
import { MAX_RENDERED_DIFF_COMBINED_CHARACTERS } from '../../../shared/large-diff-render-limit'
import {
createBoundedFileReaderModuleMock,
createFsPromisesModuleMock,
@@ -75,7 +75,7 @@ vi.mock('fs', () => ({
existsSync: existsSyncMock
}))
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) =>
vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) =>
createBoundedFileReaderModuleMock(await importOriginal<typeof BoundedFileReader>(), {
readFileMock,
statMock
@@ -96,51 +96,6 @@ describe('getDiff', () => {
})
})
it('does not read oversized working-tree files into memory', async () => {
const workingTreePath = path.join('/repo', 'dist/large.log')
gitExecFileAsyncBufferMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') })
// Route stats by path so stamp reads cannot consume the oversized-file response.
statMock.mockImplementation(async (target: string) =>
target === workingTreePath
? { isFile: () => true, size: 10 * 1024 * 1024 + 1 }
: { isFile: () => true, size: 12 }
)
const result = await getDiff('/repo', 'dist/large.log', false)
expect(readFileMock).not.toHaveBeenCalledWith(workingTreePath)
expect(result.kind).toBe('binary')
expect(result.modifiedIsBinary).toBe(true)
expect(result.modifiedContent).toBe('')
})
it('omits over-limit text bodies before returning the diff payload', async () => {
const oversizedText = 'a'.repeat(MAX_RENDERED_DIFF_COMBINED_CHARACTERS + 1)
gitExecFileAsyncBufferMock.mockResolvedValueOnce({ stdout: Buffer.from('index-content\n') })
statMock.mockResolvedValueOnce({
isFile: () => true,
size: oversizedText.length
})
readFileMock.mockResolvedValue(Buffer.from(oversizedText))
const result = await getDiff('/repo', 'dist/large.log', false)
expect(result.kind).toBe('text')
if (result.kind !== 'text') {
throw new Error('expected text diff result')
}
expect(result.originalContent).toBe('')
expect(result.modifiedContent).toBe('')
expect(result.largeDiffRenderLimit?.limited).toBe(true)
if (result.largeDiffRenderLimit?.limited !== true) {
throw new Error('expected large diff render limit')
}
expect(result.largeDiffRenderLimit.reason).toBe('character-count')
expect(result.largeDiffRenderLimit.characterCount).toBe(
oversizedText.length + 'index-content\n'.length
)
})
it('does not treat an unreadable working-tree image as a deletion', async () => {
const pngBuffer = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x00])
const workingTreePath = path.join('/repo', 'assets/unreadable.png')
@@ -1,153 +0,0 @@
import type * as RunnerModule from '../runner'
import type * as GitExecFileModule from '../command-runner/git-exec-file'
import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout'
import type * as GitProcessEnvModule from '../command-runner/git-process-env'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import path from 'node:path'
import {
createBoundedFileReaderModuleMock,
createFsPromisesModuleMock,
createGitRunnerModuleMock
} from './status-test-harness'
const {
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock,
lstatMock,
realpathMock,
readFileMock,
statMock,
rmMock,
existsSyncMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileAsyncBufferMock: vi.fn(),
gitStreamOptionsMock: vi.fn(),
lstatMock: vi.fn(),
realpathMock: vi.fn(),
readFileMock: vi.fn(),
statMock: vi.fn(),
rmMock: vi.fn(),
existsSyncMock: vi.fn()
}))
vi.mock('../runner', () =>
createGitRunnerModuleMock({
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock
})
)
vi.mock('../command-runner/git-exec-file', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitExecFileModule>()),
gitExecFileAsync: runnerMocks.gitExecFileAsync,
gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer
}
})
vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitStreamStdoutModule>()),
gitStreamStdout: runnerMocks.gitStreamStdout
}
})
vi.mock('../command-runner/git-process-env', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitProcessEnvModule>()),
gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv
}
})
vi.mock('fs/promises', () =>
createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock })
)
vi.mock('fs', () => ({
existsSync: existsSyncMock
}))
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) =>
createBoundedFileReaderModuleMock(await importOriginal<typeof BoundedFileReader>(), {
readFileMock,
statMock
})
)
import { bulkDiscardChanges, discardChanges } from './discard-changes'
import { bulkStageFiles, bulkUnstageFiles } from './staging'
describe('discardChanges', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
gitExecFileAsyncBufferMock.mockReset()
lstatMock.mockReset()
realpathMock.mockReset()
readFileMock.mockReset()
rmMock.mockReset()
lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
realpathMock.mockImplementation(async (targetPath: string) => path.resolve(targetPath))
})
it('rejects paths that traverse outside the worktree', async () => {
await expect(discardChanges('/repo', '../../etc/passwd')).rejects.toThrow(
'resolves outside the worktree'
)
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
expect(rmMock).not.toHaveBeenCalled()
})
})
describe('bulk git helpers', () => {
beforeEach(() => {
gitExecFileAsyncMock.mockReset()
lstatMock.mockReset()
realpathMock.mockReset()
rmMock.mockReset()
lstatMock.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }))
realpathMock.mockImplementation(async (targetPath: string) => path.resolve(targetPath))
})
it('preserves bulk discard action selection and original path order for path edges', async () => {
const filePaths = ['new', 'docs\\', '[ab].txt', 'docs///', 'new', 'src/file', 'docs\\']
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'docs/readme\0src/file-extra\0[ab].txt\0' })
.mockResolvedValue({ stdout: '' })
await bulkDiscardChanges('/repo', filePaths)
expect(gitExecFileAsyncMock.mock.calls.map(([args]) => args)).toEqual([
['ls-files', '-z', '--', ...filePaths.map((filePath) => `:(literal)${filePath}`)],
['restore', '--worktree', '--pathspec-from-file=-', '--pathspec-file-nul'],
['clean', '-ffdx', '--', ':(literal)new', ':(literal)new', ':(literal)src/file']
])
expect(gitExecFileAsyncMock.mock.calls[1][1].stdin).toBe(
':(literal)docs\\\0:(literal)[ab].txt\0:(literal)docs///\0:(literal)docs\\\0'
)
expect(rmMock).not.toHaveBeenCalled()
})
it('rejects bulk discard paths that traverse outside the worktree', async () => {
await expect(bulkDiscardChanges('/repo', ['src/file.ts', '../outside.txt'])).rejects.toThrow(
'resolves outside the worktree'
)
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
expect(rmMock).not.toHaveBeenCalled()
})
it('rejects embedded NUL before staging or unstaging another path', async () => {
await expect(bulkStageFiles('/repo', ['one\0two'])).rejects.toThrow('NUL')
await expect(bulkUnstageFiles('/repo', ['one\0two'])).rejects.toThrow('NUL')
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
})
})
@@ -2,7 +2,7 @@
import * as path from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as FsPromises from 'node:fs/promises'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader'
import type { GitStatusEntry } from '../../../shared/git/status/git-status-types'
import { invalidateGitBranchLineTotalInFlight } from '../../../shared/git/status/git-branch-line-total'
@@ -33,7 +33,7 @@ vi.mock('node:fs/promises', async (importOriginal) => {
}
})
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) => {
vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) => {
const actual = await importOriginal<typeof BoundedFileReader>()
return {
...actual,
@@ -1,167 +0,0 @@
import type * as RunnerModule from '../runner'
import type * as GitExecFileModule from '../command-runner/git-exec-file'
import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout'
import type * as GitProcessEnvModule from '../command-runner/git-process-env'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import {
createBoundedFileReaderModuleMock,
createFsPromisesModuleMock,
createGitRunnerModuleMock
} from './status-test-harness'
const {
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock,
lstatMock,
realpathMock,
readFileMock,
statMock,
rmMock,
existsSyncMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
gitExecFileAsyncBufferMock: vi.fn(),
gitStreamOptionsMock: vi.fn(),
lstatMock: vi.fn(),
realpathMock: vi.fn(),
readFileMock: vi.fn(),
statMock: vi.fn(),
rmMock: vi.fn(),
existsSyncMock: vi.fn()
}))
vi.mock('../runner', () =>
createGitRunnerModuleMock({
gitExecFileAsyncMock,
gitExecFileAsyncBufferMock,
gitStreamOptionsMock
})
)
vi.mock('../command-runner/git-exec-file', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitExecFileModule>()),
gitExecFileAsync: runnerMocks.gitExecFileAsync,
gitExecFileAsyncBuffer: runnerMocks.gitExecFileAsyncBuffer
}
})
vi.mock('../command-runner/git-stream-stdout', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitStreamStdoutModule>()),
gitStreamStdout: runnerMocks.gitStreamStdout
}
})
vi.mock('../command-runner/git-process-env', async (importOriginal) => {
const runnerMocks = await vi.importMock<typeof RunnerModule>('../runner')
return {
...(await importOriginal<typeof GitProcessEnvModule>()),
gitOptionalLocksDisabledEnv: runnerMocks.gitOptionalLocksDisabledEnv
}
})
vi.mock('fs/promises', () =>
createFsPromisesModuleMock({ lstatMock, realpathMock, readFileMock, statMock, rmMock })
)
vi.mock('fs', () => ({
existsSync: existsSyncMock
}))
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) =>
createBoundedFileReaderModuleMock(await importOriginal<typeof BoundedFileReader>(), {
readFileMock,
statMock
})
)
import { clearEffectiveUpstreamStatusCacheForTests } from './effective-upstream-status-cache'
import { getStatus } from './status-read'
describe('getStatus', () => {
beforeEach(() => {
clearEffectiveUpstreamStatusCacheForTests()
gitExecFileAsyncMock.mockReset()
gitExecFileAsyncBufferMock.mockReset()
gitStreamOptionsMock.mockReset()
lstatMock.mockReset()
readFileMock.mockReset()
existsSyncMock.mockReset()
// Supply empty numstat results after tests' one-shot status responses.
gitExecFileAsyncMock.mockResolvedValue({ stdout: '' })
})
it('shares one physical status read across distinct caller signals', async () => {
readFileMock.mockResolvedValue('gitdir: /repo/.git/worktrees/feature\n')
existsSyncMock.mockReturnValue(false)
let releaseStatus!: () => void
let statusCommandCalls = 0
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (args.includes('status')) {
statusCommandCalls += 1
return new Promise<{ stdout: string }>((resolve) => {
releaseStatus = () => resolve({ stdout: '' })
})
}
return Promise.resolve({ stdout: '' })
})
const firstController = new AbortController()
const secondController = new AbortController()
const firstError = new Error('first caller cancelled')
const first = getStatus('/repo', { signal: firstController.signal })
const second = getStatus('/repo', { signal: secondController.signal })
await vi.waitFor(() => expect(statusCommandCalls).toBe(1))
const underlyingSignal = gitStreamOptionsMock.mock.calls[0]?.[0].signal as AbortSignal
firstController.abort(firstError)
await expect(first).rejects.toBe(firstError)
expect(underlyingSignal?.aborted).toBe(false)
releaseStatus()
await expect(second).resolves.toMatchObject({ entries: [] })
expect(statusCommandCalls).toBe(1)
})
it('aborts physical status work after its last live caller cancels', async () => {
readFileMock.mockResolvedValue('gitdir: /repo/.git/worktrees/feature\n')
existsSyncMock.mockReturnValue(false)
let statusCommandCalls = 0
let rejectStatus!: (error: unknown) => void
gitExecFileAsyncMock.mockImplementation((args: string[]) => {
if (!args.includes('status')) {
return Promise.resolve({ stdout: '' })
}
statusCommandCalls += 1
if (statusCommandCalls > 1) {
return Promise.resolve({ stdout: '' })
}
return new Promise<{ stdout: string }>((_resolve, reject) => {
rejectStatus = reject
})
})
const firstController = new AbortController()
const secondController = new AbortController()
const first = getStatus('/repo', { signal: firstController.signal })
const second = getStatus('/repo', { signal: secondController.signal })
await vi.waitFor(() => expect(statusCommandCalls).toBe(1))
const underlyingSignal = gitStreamOptionsMock.mock.calls[0]?.[0].signal as AbortSignal
underlyingSignal.addEventListener('abort', () => rejectStatus(underlyingSignal.reason), {
once: true
})
firstController.abort(new Error('first cancelled'))
await expect(first).rejects.toThrow('first cancelled')
expect(underlyingSignal.aborted).toBe(false)
secondController.abort(new Error('second cancelled'))
await expect(second).rejects.toThrow('second cancelled')
expect(underlyingSignal.aborted).toBe(true)
await expect(getStatus('/repo')).resolves.toMatchObject({ entries: [] })
expect(statusCommandCalls).toBe(2)
})
})
@@ -3,7 +3,7 @@ import type * as GitExecFileModule from '../command-runner/git-exec-file'
import type * as GitStreamStdoutModule from '../command-runner/git-stream-stdout'
import type * as GitProcessEnvModule from '../command-runner/git-process-env'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader'
import path from 'node:path'
import {
createBoundedFileReaderModuleMock,
@@ -74,13 +74,13 @@ vi.mock('fs', () => ({
existsSync: existsSyncMock
}))
vi.mock('../../../shared/node-bounded-file-reader', async (importOriginal) =>
vi.mock('../../../shared/file-content/node-bounded-file-reader', async (importOriginal) =>
createBoundedFileReaderModuleMock(await importOriginal<typeof BoundedFileReader>(), {
readFileMock,
statMock
})
)
import { clearSubmodulePathsCacheForTests, listSubmodulePaths } from './submodule-paths'
import { clearSubmodulePathsCacheForTests } from './submodule-paths'
import { getDiff } from './file-diff'
describe('submodule diff routing', () => {
@@ -143,30 +143,3 @@ describe('submodule diff routing', () => {
await expect(getDiff(PARENT, '../evil', false)).rejects.toThrow('Access denied')
})
})
describe('listSubmodulePaths', () => {
beforeEach(() => {
clearSubmodulePathsCacheForTests()
gitExecFileAsyncMock.mockReset()
})
it('keeps cached .gitmodules paths separate per WSL distro', async () => {
gitExecFileAsyncMock.mockImplementation((_args: string[], options?: { wslDistro?: string }) =>
Promise.resolve({
stdout:
options?.wslDistro === 'debian'
? 'submodule.lib.path\ndebian-lib\0'
: 'submodule.lib.path\nubuntu-lib\0'
})
)
await expect(listSubmodulePaths('/repo', { wslDistro: 'ubuntu' })).resolves.toEqual([
'ubuntu-lib'
])
await expect(listSubmodulePaths('/repo', { wslDistro: 'debian' })).resolves.toEqual([
'debian-lib'
])
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(2)
})
})
@@ -1,5 +1,5 @@
import type { Mock } from 'vitest'
import type * as BoundedFileReader from '../../../shared/node-bounded-file-reader'
import type * as BoundedFileReader from '../../../shared/file-content/node-bounded-file-reader'
type MockFn = Mock
@@ -1,7 +1,7 @@
import {
IMAGE_AND_PDF_PREVIEW_MIME_TYPES,
filePreviewExtension
} from '../../../shared/file-preview-kind'
} from '../../../shared/file-preview/file-preview-kind'
import type { GitRuntimeOptions } from '../git-runtime-options'
import { gitReadOptionsForWorktree } from '../git-runtime-options'
import { gitExecFileAsync } from '../runner'
+2 -2
View File
@@ -6,7 +6,7 @@ import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { app, BrowserWindow, dialog, ipcMain, type IpcMainInvokeEvent } from 'electron'
import type { AppIdentity } from '../../shared/app-identity'
import type { MarkdownDocument } from '../../shared/filesystem-entry-types'
import type { MarkdownDocument } from '../../shared/file-listing/file-document'
import type { FloatingTerminalCwdRequest } from '../../shared/ui-chrome-types'
import { relaunchApp, runBeforeRelaunchCleanup } from '../startup/quit/app-relaunch'
import { setWindowMaterialSuppressed } from '../window/window-material-suppression'
@@ -29,7 +29,7 @@ import {
import {
isMarkdownDocumentName,
markdownDocumentFromFilePath
} from '../../shared/markdown-document-paths'
} from '../../shared/file-listing/markdown-document-paths'
import { registerMacSymbolicHotkeysProbeHandler } from './macos-symbolic-hotkeys-probe'
import {
registerRendererShutdownCheckpointHandler,
+1 -1
View File
@@ -5,7 +5,7 @@ import {
DOC_PREVIEW_LINK_CLICK_CHANNEL,
DOC_PREVIEW_MINT_GRANT_CHANNEL,
DOC_PREVIEW_REVOKE_GRANT_CHANNEL
} from '../../shared/doc-preview-scheme'
} from '../../shared/document-preview/doc-preview-scheme'
import { browserManager } from '../browser/browser-manager'
import { reportDocPreviewLinkClick } from '../browser/document-preview/doc-preview-guest-policy'
import {

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