mirror of
https://github.com/stablyai/orca.git
synced 2026-11-15 18:37:24 +00:00
Merge main for final maintenance validation
This commit is contained in:
@@ -483,7 +483,7 @@
|
||||
2 test-no-wall-clock:src/main/grok/grok-hook-stdin-no-eof.test.ts
|
||||
3 test-no-wall-clock:src/main/ipc/runtime-environments/runtime-environment-request-connections.test.ts
|
||||
1 test-no-wall-clock:src/main/ipc/terminal-render-desync-evidence.test.ts
|
||||
5 test-no-wall-clock:src/main/ipc/worktrees-orphan-directory-cleanup.test.ts
|
||||
2 test-no-wall-clock:src/main/ipc/worktrees-orphan-directory-cleanup.test.ts
|
||||
2 test-no-wall-clock:src/main/ipc/worktrees/git/worktree-git-status-attribution-real-git.test.ts
|
||||
2 test-no-wall-clock:src/main/macos-permissions/macos-tcc-log-stream-orphans.test.ts
|
||||
4 test-no-wall-clock:src/main/managed-server/activation/orcad-exited-own-fence-mutation-race.test.ts
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -235,7 +235,6 @@
|
||||
"config/scripts/typecheck/project-execution/run-typecheck-projects-in-parallel.test.mjs": 182,
|
||||
"config/scripts/tool-invocation/script-entry-detection.test.mjs": 107,
|
||||
"config/scripts/test-fixtures/script-copy-closure/script-module-dependencies.test.mjs": 62,
|
||||
"config/scripts/orcad-distribution/server-bundle/session-scanner-service-smoke.test.mjs": 562,
|
||||
"config/scripts/ci/workflow-contracts/setup-pnpm-action.test.mjs": 421,
|
||||
"config/scripts/electron-installation/shared-dist-cache/shared-electron-dist-cache.test.ts": 140,
|
||||
"config/scripts/native-build/node-addons/shared-native-build.test.mjs": 127,
|
||||
@@ -2186,12 +2185,9 @@
|
||||
"src/main/git/remotes/worktree-push-target-setup.test.ts": 491,
|
||||
"src/main/ipc/worktree-symlink-reconciliation.real.test.ts": 410,
|
||||
"src/main/ipc/worktree-symlinks.test.ts": 152,
|
||||
"src/main/ipc/worktrees-delete-pty-teardown.test.ts": 1934,
|
||||
"src/main/ipc/worktrees-issue-command-overrides.test.ts": 1594,
|
||||
"src/main/ipc/worktrees-orphan-directory-cleanup.test.ts": 1486,
|
||||
"src/main/ipc/worktrees-removal-recovery.test.ts": 1971,
|
||||
"src/main/ipc/worktrees-remove-preflight.test.ts": 1415,
|
||||
"src/main/ipc/worktrees-ssh-repo-owner-resolution.test.ts": 1447,
|
||||
"src/main/ipc/worktrees/listing/detected-provider-listing-catalog-version.test.ts": 650,
|
||||
"src/main/ipc/worktrees/listing/detected-worktree-scan-hygiene-gate.test.ts": 105,
|
||||
"src/main/ipc/worktrees/listing/detected-worktree-scan-listing-distro.test.ts": 880,
|
||||
|
||||
-49
@@ -1,49 +0,0 @@
|
||||
import { build } from 'esbuild'
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { smokeSessionScannerService } from './session-scanner-service-smoke.mjs'
|
||||
import {
|
||||
externalNativeAddons,
|
||||
ORCAD_CHILD_ENTRY_POINTS,
|
||||
ORCAD_EXTERNAL_MODULES,
|
||||
orcadChildOutputFilename
|
||||
} from './orcad-entry-build.mjs'
|
||||
|
||||
const ENTRY = orcadChildOutputFilename(ORCAD_CHILD_ENTRY_POINTS.sessionScanner)
|
||||
const directories = []
|
||||
let builtDirectory
|
||||
|
||||
function fixtureDirectory() {
|
||||
const directory = mkdtempSync(join(tmpdir(), 'orca-session-scanner-smoke-test-'))
|
||||
directories.push(directory)
|
||||
return directory
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
builtDirectory = fixtureDirectory()
|
||||
await build({
|
||||
entryPoints: [resolve(ORCAD_CHILD_ENTRY_POINTS.sessionScanner)],
|
||||
outfile: join(builtDirectory, ENTRY),
|
||||
bundle: true,
|
||||
platform: 'node',
|
||||
target: 'node18',
|
||||
format: 'cjs',
|
||||
external: ORCAD_EXTERNAL_MODULES,
|
||||
plugins: [externalNativeAddons],
|
||||
logLevel: 'silent'
|
||||
})
|
||||
}, 60_000)
|
||||
|
||||
afterAll(() => {
|
||||
for (const directory of directories) {
|
||||
rmSync(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
describe('session scanner service build smoke', () => {
|
||||
it('lists a seeded session through the built entry', () => {
|
||||
expect(() => smokeSessionScannerService(builtDirectory)).not.toThrow()
|
||||
}, 60_000)
|
||||
})
|
||||
@@ -39,8 +39,7 @@
|
||||
"../src/types/**/*"
|
||||
],
|
||||
"exclude": [
|
||||
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
|
||||
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts"
|
||||
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts"
|
||||
],
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
"extends": "./tsconfig.web.json",
|
||||
"include": [
|
||||
"../src/main/runtime/orchestration/terminal-authority/structured-sessions/structured-chat-coordinator-mail.test.ts",
|
||||
"../src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts",
|
||||
"../src/renderer/src/components/task-page/linear/task-page-linear-detail-query.test.tsx",
|
||||
"../src/renderer/src/runtime/observed-provider-accounts.test.tsx",
|
||||
"../src/renderer/src/components/status-bar/ClaudeSwitcherMenu.observation.test.tsx",
|
||||
|
||||
@@ -14,8 +14,7 @@ const contracts = [
|
||||
'src/main/codex-usage/scanner-incremental-append.test.ts',
|
||||
'src/main/usage/source-input/jsonl/jsonl-file-reader.test.ts',
|
||||
'config/scripts/static-analysis/oxlint-contracts/app-store-performance-plugin.test.mjs',
|
||||
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs',
|
||||
'src/main/runtime/agent-session/structured-agent-session-chat-wait-work-state.test.ts'
|
||||
'config/scripts/static-analysis/oxlint-contracts/quadratic-buffer-concat-plugin.test.mjs'
|
||||
]
|
||||
for (const contract of contracts) {
|
||||
if (!existsSync(resolve(contract))) {
|
||||
|
||||
@@ -233,21 +233,6 @@ orca chat rename --name "Migrate auth"
|
||||
|
||||
Renames a chat tab, the same as renaming it by hand. `--session` takes the `sessionId` that `orca agent launch` prints. Run inside a chat, it defaults to that chat; with `--environment` it is required.
|
||||
|
||||
Agents that run as chats are read and messaged with `chat` commands. `--session` takes the session id from `chat list` or the handle `agent launch` returns.
|
||||
|
||||
```bash
|
||||
orca chat list --json
|
||||
orca chat list --state working --json
|
||||
orca chat read --session <session> --limit 10 --json
|
||||
orca chat send --session <session> --text "Run the tests, then summarize failures" --json
|
||||
orca chat send --session <session> --text "<message>" --wait --timeout-ms 600000 --json
|
||||
orca chat wait --session <session> --timeout-ms 600000 --json
|
||||
```
|
||||
|
||||
`chat read` returns the newest messages, tool calls, errors, approvals and questions; an approval or question waiting for an answer has `pending: true`. `chat send` sends the text as your message. While the agent is working, hosts with a message queue hold it until the turn ends and report `delivery: "queued"`. A chat that restarted since it was read refuses the send. `--text-file -` reads the message from stdin.
|
||||
|
||||
`chat send --wait` and `chat wait` return once the chat's own turn settles, in the words `chat list` uses: `settled: "done"`, or `settled: "blocked"` when an approval or question needs an answer. Background agents the chat started can still show as `working` or `waiting` in `chat list`. They print the entries since the last user message. A wait past `--timeout-ms` returns `settled: "timeout"`, and a message held in a stopped or failed queue returns `settled: "held"`; both exit 1. `chat read --json` returns a `cursor` for the newest row read, and `truncated: true` when older rows it needed were past the 200-row read. `chat list --state` takes `working`, `blocked`, `waiting` or `done`. Paired hosts (`--environment`, `--pairing-code`) can list chats but not read, send or wait yet.
|
||||
|
||||
## Files
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { hostOs } from './host-os.web'
|
||||
|
||||
function agent(userAgent: string, platform = '', maxTouchPoints = 0) {
|
||||
Object.defineProperty(navigator, 'userAgent', { value: userAgent, configurable: true })
|
||||
Object.defineProperty(navigator, 'platform', { value: platform, configurable: true })
|
||||
Object.defineProperty(navigator, 'maxTouchPoints', { value: maxTouchPoints, configurable: true })
|
||||
}
|
||||
|
||||
afterEach(() => agent(''))
|
||||
|
||||
describe("the page's host OS", () => {
|
||||
it('reads the phone off the WebView user agent', () => {
|
||||
agent(
|
||||
'Mozilla/5.0 (iPhone; CPU iPhone OS 26_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
|
||||
)
|
||||
expect(hostOs()).toBe('ios')
|
||||
agent(
|
||||
'Mozilla/5.0 (Linux; Android 17; sdk_gphone64_arm64 Build/CP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/144.0 Mobile Safari/537.36'
|
||||
)
|
||||
expect(hostOs()).toBe('android')
|
||||
})
|
||||
|
||||
it('reads an iPad that still names itself in the user agent', () => {
|
||||
agent(
|
||||
'Mozilla/5.0 (iPad; CPU OS 18_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
|
||||
)
|
||||
expect(hostOs()).toBe('ios')
|
||||
})
|
||||
|
||||
it('takes an iPad, which reports a Mac, by its touch points', () => {
|
||||
agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15', 'MacIntel', 5)
|
||||
expect(hostOs()).toBe('ios')
|
||||
agent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15', 'MacIntel', 0)
|
||||
expect(hostOs()).toBe('web')
|
||||
})
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import type { HostOs } from './host-os'
|
||||
|
||||
export type { HostOs } from './host-os'
|
||||
|
||||
// Use the phone OS for keyboard/inset arithmetic: Platform.OS is web here; iPadOS needs the Mac-plus-touch heuristic.
|
||||
// Platform.OS is web here: read the phone OS for keyboard/inset arithmetic (iPadOS needs the Mac-plus-touch heuristic) and a desktop Mac for Cmd chords.
|
||||
export function hostOs(): HostOs {
|
||||
const agent = globalThis.navigator?.userAgent ?? ''
|
||||
if (/iP(ad|hone|od)/.test(agent)) {
|
||||
@@ -11,5 +11,8 @@ export function hostOs(): HostOs {
|
||||
if (globalThis.navigator?.platform === 'MacIntel' && globalThis.navigator.maxTouchPoints > 1) {
|
||||
return 'ios'
|
||||
}
|
||||
return agent.includes('Android') ? 'android' : 'web'
|
||||
if (agent.includes('Android')) {
|
||||
return 'android'
|
||||
}
|
||||
return agent.includes('Macintosh') ? 'macos' : 'web'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { hostOs } from './host-os'
|
||||
|
||||
/** The submit chord's modifier: Cmd on an Apple keyboard (iPhone, iPad, Mac), Ctrl elsewhere. */
|
||||
export function primaryModifierKey(): 'Meta' | 'Control' {
|
||||
const os = hostOs()
|
||||
return os === 'ios' || os === 'macos' ? 'Meta' : 'Control'
|
||||
}
|
||||
-151
@@ -80,48 +80,6 @@ describe('mobile composer modifier submit in the paired web page', () => {
|
||||
return input
|
||||
}
|
||||
|
||||
async function render(props: Partial<ComposerProps> = {}) {
|
||||
function Draft() {
|
||||
const [value, setValue] = useState(props.value ?? ' hello ')
|
||||
const composer = (
|
||||
<MobileNativeChatComposer
|
||||
sendSurfaceId="keyboard-test"
|
||||
getSendCompletionGeneration={() => 0}
|
||||
getComposerEditGeneration={() => 0}
|
||||
{...props}
|
||||
value={value}
|
||||
onChangeText={setValue}
|
||||
onSend={onSend}
|
||||
/>
|
||||
)
|
||||
return props.editSession ? (
|
||||
<div data-testid="queue-viewport" style={{ overflow: 'hidden' }}>
|
||||
{composer}
|
||||
</div>
|
||||
) : (
|
||||
composer
|
||||
)
|
||||
}
|
||||
await act(async () => root.render(<Draft />))
|
||||
await act(async () => field().focus())
|
||||
}
|
||||
|
||||
async function key(flags: KeyboardEventInit = {}) {
|
||||
// Enter's base shape was captured in the native iOS shell; modifier flags are supplied, not recorded chords.
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'Enter',
|
||||
code: 'Enter',
|
||||
keyCode: 13,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
...flags
|
||||
})
|
||||
await act(async () => {
|
||||
field().dispatchEvent(event)
|
||||
})
|
||||
return event
|
||||
}
|
||||
|
||||
async function selectEnd() {
|
||||
await act(async () => {
|
||||
const input = field()
|
||||
@@ -172,50 +130,6 @@ describe('mobile composer modifier submit in the paired web page', () => {
|
||||
expect(input.value).toBe('retained draft')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{},
|
||||
{ shiftKey: true },
|
||||
{ ctrlKey: true },
|
||||
{ metaKey: true, shiftKey: true },
|
||||
{ metaKey: true, altKey: true },
|
||||
{ metaKey: true, ctrlKey: true },
|
||||
{ metaKey: true, isComposing: true },
|
||||
{ metaKey: true, keyCode: 229 }
|
||||
])('leaves editing and composition keys untouched: %j', async (flags) => {
|
||||
await render()
|
||||
expect((await key(flags)).defaultPrevented).toBe(false)
|
||||
expect(onSend).not.toHaveBeenCalled()
|
||||
expect(field().value).toBe(' hello ')
|
||||
})
|
||||
|
||||
it.each([
|
||||
{ value: '@rea', expected: '@README.md ', filePaths: ['README.md', 'src/read.ts'] },
|
||||
{ value: '/comp', expected: '/compact ', filePaths: [] }
|
||||
])(
|
||||
'completes the first existing menu row for $value without submitting',
|
||||
async ({ value, expected, filePaths }) => {
|
||||
await render({
|
||||
value,
|
||||
filePaths,
|
||||
agent: 'codex',
|
||||
structured: {
|
||||
catalog: { reported: [{ name: 'compact', kind: 'command' }], conversationCommands: [] },
|
||||
files: [],
|
||||
onRemoveFile: vi.fn(),
|
||||
onSlashMenuOpen: vi.fn()
|
||||
}
|
||||
})
|
||||
await selectEnd()
|
||||
expect((await key({ metaKey: true })).defaultPrevented).toBe(true)
|
||||
expect(field().value).toBe(expected)
|
||||
expect(onSend).not.toHaveBeenCalled()
|
||||
expect(document.activeElement).toBe(field())
|
||||
expect((await key({ metaKey: true, repeat: true })).defaultPrevented).toBe(true)
|
||||
expect(onSend).not.toHaveBeenCalled()
|
||||
expect(field().value).toBe(expected)
|
||||
}
|
||||
)
|
||||
|
||||
function queuedGeometry() {
|
||||
const anchor = { top: 430, width: 390, clipTop: 250, clipHeight: 300 }
|
||||
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (
|
||||
@@ -232,16 +146,6 @@ describe('mobile composer modifier submit in the paired web page', () => {
|
||||
return anchor
|
||||
}
|
||||
|
||||
async function queuedMention() {
|
||||
await render({
|
||||
value: '@rea',
|
||||
filePaths: ['README.md', 'src/read.ts'],
|
||||
agent: 'codex',
|
||||
editSession: { cancel: vi.fn(), refuseCommand: () => false, locked: false }
|
||||
})
|
||||
await selectEnd()
|
||||
}
|
||||
|
||||
function suggestion() {
|
||||
return container.querySelector<HTMLElement>('[aria-label="README.md"]')
|
||||
}
|
||||
@@ -327,59 +231,4 @@ describe('mobile composer modifier submit in the paired web page', () => {
|
||||
expect(suggestion()).toBeNull()
|
||||
expect(container.querySelector('[aria-label="queue.ts"]')).toBeNull()
|
||||
})
|
||||
|
||||
it('picks a suggestion outside the clipped queue while keeping the edited draft focused', async () => {
|
||||
queuedGeometry()
|
||||
await queuedMention()
|
||||
const input = field()
|
||||
const row = suggestion()
|
||||
expect(row).not.toBeNull()
|
||||
const queue = container.querySelector('[data-testid="queue-viewport"]')!
|
||||
expect(queue.contains(row)).toBe(false)
|
||||
expect(container.contains(row)).toBe(true)
|
||||
const down = new MouseEvent('mousedown', { bubbles: true, cancelable: true })
|
||||
await act(async () => {
|
||||
row!.dispatchEvent(down)
|
||||
row!.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }))
|
||||
row!.click()
|
||||
})
|
||||
expect(down.defaultPrevented).toBe(true)
|
||||
expect(field()).toBe(input)
|
||||
expect(input.value).toBe('@README.md ')
|
||||
expect(document.activeElement).toBe(input)
|
||||
expect(suggestion()).toBeNull()
|
||||
expect(onSend).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('retires scrolled-out or hidden editor suggestions and restores them from current geometry', async () => {
|
||||
const anchor = queuedGeometry()
|
||||
await queuedMention()
|
||||
expect(
|
||||
suggestion(),
|
||||
JSON.stringify({
|
||||
value: field().value,
|
||||
caret: field().selectionStart,
|
||||
focused: document.activeElement === field(),
|
||||
viewport: window.innerHeight,
|
||||
text: container.textContent?.slice(0, 120)
|
||||
})
|
||||
).not.toBeNull()
|
||||
anchor.top = 900
|
||||
await act(async () => window.dispatchEvent(new Event('scroll')))
|
||||
expect(suggestion()).toBeNull()
|
||||
anchor.top = 430
|
||||
await act(async () => window.dispatchEvent(new Event('scroll')))
|
||||
expect(suggestion()).not.toBeNull()
|
||||
anchor.clipTop = 450
|
||||
anchor.clipHeight = 0
|
||||
await act(async () => window.dispatchEvent(new Event('resize')))
|
||||
expect(suggestion()).toBeNull()
|
||||
anchor.clipTop = 250
|
||||
anchor.clipHeight = 300
|
||||
anchor.width = 0
|
||||
await act(async () => window.dispatchEvent(new Event('resize')))
|
||||
expect(suggestion()).toBeNull()
|
||||
expect(field().value).toBe('@rea')
|
||||
expect(document.activeElement).toBe(field())
|
||||
})
|
||||
})
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type TextInputInstance
|
||||
} from 'react-native'
|
||||
import { useKeyboardOcclusion } from '../../../platform/keyboard-occlusion'
|
||||
import { hostOs } from '../../../platform/host-os'
|
||||
import { primaryModifierKey } from '../../../platform/primary-modifier-key'
|
||||
import { useTextInputContentHeight } from '../../../platform/text-input-content-height'
|
||||
import { useTextInputSelectionReveal } from '../../../platform/text-input-selection-reveal.web'
|
||||
import { colors } from '../../../theme/mobile-theme'
|
||||
@@ -120,7 +120,9 @@ export function MobileNativeChatComposerField({
|
||||
key.keyCode === 229 ||
|
||||
key.shiftKey ||
|
||||
key.altKey ||
|
||||
!(hostOs() === 'ios' ? key.metaKey && !key.ctrlKey : key.ctrlKey && !key.metaKey)
|
||||
!(primaryModifierKey() === 'Meta'
|
||||
? key.metaKey && !key.ctrlKey
|
||||
: key.ctrlKey && !key.metaKey)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
+2
-3
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { hostOs } from '../../../platform/host-os'
|
||||
import { primaryModifierKey } from '../../../platform/primary-modifier-key'
|
||||
import { createNativeChatSteerChordPreviewHook } from '../../../../../src/shared/native-chat/input/use-native-chat-steer-chord-preview'
|
||||
import type { MobileNativeChatSteerChordPreviewInput } from './use-mobile-native-chat-steer-chord-preview'
|
||||
|
||||
@@ -36,8 +36,7 @@ export function useMobileNativeChatSteerChordPreview({
|
||||
steerHead && (() => steerHead.run(alternateSteers)),
|
||||
sendAlternate,
|
||||
pickerOpen,
|
||||
// The field's own submit chord: Cmd on an iPhone or iPad keyboard, Ctrl elsewhere.
|
||||
hostOs() === 'ios' ? 'Meta' : 'Control'
|
||||
primaryModifierKey()
|
||||
)
|
||||
const lit = chord.preview === 'steer-queued'
|
||||
const light = steerHead?.light
|
||||
|
||||
@@ -894,7 +894,11 @@ final class Provider {
|
||||
throw ProviderError.coded("accessibility_error", "AXUIElementSetAttributeValue failed with \(result.rawValue)")
|
||||
}
|
||||
let verification: [String: Any]
|
||||
switch coercion.compare(readback: rawAttributeValue(record.element, kAXValueAttribute as String)) {
|
||||
let readback = settledValueReadback(record.element) { readback in
|
||||
if case .mismatch = coercion.compare(readback: readback) { return false }
|
||||
return true
|
||||
}
|
||||
switch coercion.compare(readback: readback) {
|
||||
case let .match(actualPreview):
|
||||
verification = verifiedAction(property: "value", expected: expected, actualPreview: actualPreview)
|
||||
case let .mismatch(actualPreview):
|
||||
@@ -1751,6 +1755,19 @@ private func rawStringAttribute(_ element: AXUIElement, _ attribute: String) ->
|
||||
return value as? String
|
||||
}
|
||||
|
||||
/// Reads the value until `settled` accepts it: Chromium answers from a cache that trails a successful write by about 100 ms.
|
||||
private func settledValueReadback(_ element: AXUIElement, settled: (CFTypeRef) -> Bool) -> CFTypeRef? {
|
||||
var readback: CFTypeRef?
|
||||
// Why: settle counts only its sleeps, and one slow or failed AX read can take the full 3 s timeout.
|
||||
let deadline = CFAbsoluteTimeGetCurrent() + 0.5
|
||||
_ = PermissionTrustSettling.settle(timeoutMs: 500, intervalMs: 25) {
|
||||
readback = rawAttributeValue(element, kAXValueAttribute as String)
|
||||
guard let readback, CFAbsoluteTimeGetCurrent() < deadline else { return true }
|
||||
return settled(readback)
|
||||
}
|
||||
return readback
|
||||
}
|
||||
|
||||
private func rawAttributeValue(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? {
|
||||
var value: CFTypeRef?
|
||||
guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else {
|
||||
@@ -2937,7 +2954,9 @@ private enum Input {
|
||||
|
||||
private enum TextInput {
|
||||
static func replaceSelection(_ element: AXUIElement, with text: String) throws -> [String: Any]? {
|
||||
guard isSettable(element, kAXValueAttribute as String),
|
||||
// Why: Chromium applies AX value writes without the input events pages listen to; a contenteditable gets none, so editors like Discord's never see the text.
|
||||
guard !BackgroundInputTransport.isChromiumNode(element),
|
||||
isSettable(element, kAXValueAttribute as String),
|
||||
let current = rawStringAttribute(element, kAXValueAttribute as String)
|
||||
else {
|
||||
return nil
|
||||
@@ -2958,8 +2977,14 @@ private enum TextInput {
|
||||
return nil
|
||||
}
|
||||
setSelectedTextRange(element, CFRange(location: startOffset + text.utf16.count, length: 0))
|
||||
guard rawStringAttribute(element, kAXValueAttribute as String) == next else {
|
||||
return nil
|
||||
// Why: a cached, out-of-process AX tree can show the old value for a moment; any other value is final.
|
||||
let readback = settledValueReadback(element) { next == current || ($0 as? String) != current } as? String
|
||||
guard readback == next else {
|
||||
// Why: typing the text as keys after a write that landed enters it twice, so only an unchanged field falls back.
|
||||
if readback == current {
|
||||
return nil
|
||||
}
|
||||
return unverifiedAction(reason: "accessibility_action_unasserted", expected: text, actualPreview: readback.map { preview($0) })
|
||||
}
|
||||
return verifiedAction(
|
||||
property: "focusedText",
|
||||
|
||||
+1
-1
@@ -326,7 +326,7 @@ public enum BackgroundInputTransport {
|
||||
}
|
||||
}
|
||||
|
||||
private static func isChromiumNode(_ element: AXUIElement) -> Bool {
|
||||
public static func isChromiumNode(_ element: AXUIElement) -> Bool {
|
||||
var names: CFArray?
|
||||
guard AXUIElementCopyAttributeNames(element, &names) == .success, let names = names as? [String] else {
|
||||
return false
|
||||
|
||||
@@ -28,9 +28,9 @@ Prefer `--json` for agent-driven calls. If the CLI is missing, say so explicitly
|
||||
|
||||
A full handoff transfers ownership to another agent or worktree, then the original agent stops. Treat requests phrased as "hand off", "handoff", "handover", "give this to another agent", "give this to another worktree", "another agent", or "another worktree" as full handoffs unless the user expects the result back ("have another agent review this and report") or explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use decision gates, or manage ask/reply.
|
||||
|
||||
A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the `terminal send` receipt reported `accepted: true` or `chat send` reported `delivery` `submitted` or `queued`. Do not wait for the receiving agent to finish.
|
||||
A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the send receipt reported `accepted: true`. Do not wait for the receiving agent to finish.
|
||||
|
||||
Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with `terminal send` or `chat send` for an agent that is already running.
|
||||
Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with terminal commands for an agent that is already running.
|
||||
|
||||
For local work in the caller’s project, omit `--repo` and `--project`. Pass one to target another project or when Orca asks you to disambiguate; do not pick a repo from a list for unambiguous same-project work. The project comes from the caller’s directory, not the project visible in the app. Paired-server calls require an explicit server-side target.
|
||||
|
||||
@@ -62,14 +62,6 @@ Existing-terminal handoff:
|
||||
ORCA terminal send --terminal <handle> --text "<task brief>" --enter --json
|
||||
```
|
||||
|
||||
Existing-chat handoff, for an agent that runs as a chat (`outcome.kind` `structured`):
|
||||
|
||||
```text
|
||||
ORCA chat send --session <session> --text "<task brief>" --json
|
||||
ORCA chat send --session <session> --text "<message>" --wait --timeout-ms 600000 --json
|
||||
ORCA chat wait --session <session> --timeout-ms 600000 --json
|
||||
```
|
||||
|
||||
## Starting agents
|
||||
|
||||
`worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands.
|
||||
@@ -281,24 +273,6 @@ Terminal rules:
|
||||
- For long output, use cursor reads. After a limited tail preview, page from `oldestCursor`; after a cursor read, continue with `nextCursor` while `limited` is true and `nextCursor !== latestCursor`.
|
||||
- `--direction vertical` splits left/right. `--direction horizontal` splits top/bottom.
|
||||
|
||||
## Chats
|
||||
|
||||
Agents launched as chats are read and messaged with `chat`, not `terminal`. `chat list` names each chat's workspace, agent, state and last reply; `--session` takes the `session` it reports or the `handle` a launch returned.
|
||||
|
||||
```text
|
||||
ORCA chat list --json
|
||||
ORCA chat list --state working --json
|
||||
ORCA chat read --session <session> --limit 10 --json
|
||||
ORCA chat send --session <session> --text "<message>" --json
|
||||
```
|
||||
|
||||
- `chat read` returns messages, tool calls, errors, and approvals or questions; `pending: true` marks one waiting for the user.
|
||||
- `chat send` sends the text as the user's message. While the agent works, a host with a message queue holds it until the turn ends and reports `delivery: "queued"`.
|
||||
- A refused send was not delivered. Read the chat again before resending.
|
||||
- `chat send --wait` (or `chat wait`) returns when the chat settles, using `chat list` states: `settled: "done"`, or `"blocked"` on an approval or question, with the entries since the last user message; `settled: "timeout"` or `"held"` (queued message stopped or failed) exits 1. Pass `--timeout-ms`. Long or quoted text goes through `--text-file -` on stdin.
|
||||
- Paired hosts can `chat list` only; read, send and wait run on the host machine.
|
||||
- When relaying for a user from outside Orca (for example a voice or messaging assistant on the same machine), report from `chat list` and `chat read`, repeat an instruction back and get the user's confirmation before `chat send`, and send the user's words without adding instructions.
|
||||
|
||||
<!-- host-capability: artifact-publishing -->
|
||||
|
||||
## Artifacts
|
||||
|
||||
@@ -256,9 +256,9 @@ const ORCA_CLI_MARKDOWN = [
|
||||
"",
|
||||
"A full handoff transfers ownership to another agent or worktree, then the original agent stops. Treat requests phrased as \"hand off\", \"handoff\", \"handover\", \"give this to another agent\", \"give this to another worktree\", \"another agent\", or \"another worktree\" as full handoffs unless the user expects the result back (\"have another agent review this and report\") or explicitly asks to supervise, monitor, wait for results, track completion, coordinate a DAG, use decision gates, or manage ask/reply.",
|
||||
"",
|
||||
"A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the `terminal send` receipt reported `accepted: true` or `chat send` reported `delivery` `submitted` or `queued`. Do not wait for the receiving agent to finish.",
|
||||
"A handoff is done when the new worktree id and agent handle have been reported and the prompt was delivered: the launch's `prompt.outcome` is `journaled` or `handed-to-terminal`, or, for an agent that was already running, the send receipt reported `accepted: true`. Do not wait for the receiving agent to finish.",
|
||||
"",
|
||||
"Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with `terminal send` or `chat send` for an agent that is already running.",
|
||||
"Do not use `orca orchestration task-create`, `orca orchestration dispatch --inject`, or `orca orchestration check --wait` for full handoffs. `task-create` is also forbidden because it records coordinator-owned tracking state; if a task row is needed, the user asked for supervised orchestration. Deliver the prompt with the agent launch, or with terminal commands for an agent that is already running.",
|
||||
"",
|
||||
"For local work in the caller’s project, omit `--repo` and `--project`. Pass one to target another project or when Orca asks you to disambiguate; do not pick a repo from a list for unambiguous same-project work. The project comes from the caller’s directory, not the project visible in the app. Paired-server calls require an explicit server-side target.",
|
||||
"",
|
||||
@@ -290,14 +290,6 @@ const ORCA_CLI_MARKDOWN = [
|
||||
"ORCA terminal send --terminal <handle> --text \"<task brief>\" --enter --json",
|
||||
"```",
|
||||
"",
|
||||
"Existing-chat handoff, for an agent that runs as a chat (`outcome.kind` `structured`):",
|
||||
"",
|
||||
"```text",
|
||||
"ORCA chat send --session <session> --text \"<task brief>\" --json",
|
||||
"ORCA chat send --session <session> --text \"<message>\" --wait --timeout-ms 600000 --json",
|
||||
"ORCA chat wait --session <session> --timeout-ms 600000 --json",
|
||||
"```",
|
||||
"",
|
||||
"## Starting agents",
|
||||
"",
|
||||
"`worktree create --agent` (new checkout) and `agent launch` (existing worktree) are how to start an agent. They go through Orca's agent launch, the same one the app's new-agent tab uses: the user's Chat | CLI choice for that agent decides whether it opens as a chat or a terminal, and the result reports which (`outcome.kind`) and why (`receipt.detail`). When a chat is not possible, such as for an agent without chat support, the launch starts a terminal and the receipt says so. `--surface chat|terminal` picks one for that launch instead of the setting; pass it only when the user asked for a chat or a terminal. `--surface chat` is refused when Orca can establish before starting anything that the agent cannot open as a chat. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable only after a new workspace is created, Orca keeps that workspace, its setup and default tabs, then opens a terminal; the receipt explains the fallback. `terminal create` makes a terminal for shells and commands.",
|
||||
@@ -509,24 +501,6 @@ const ORCA_CLI_MARKDOWN = [
|
||||
"- For long output, use cursor reads. After a limited tail preview, page from `oldestCursor`; after a cursor read, continue with `nextCursor` while `limited` is true and `nextCursor !== latestCursor`.",
|
||||
"- `--direction vertical` splits left/right. `--direction horizontal` splits top/bottom.",
|
||||
"",
|
||||
"## Chats",
|
||||
"",
|
||||
"Agents launched as chats are read and messaged with `chat`, not `terminal`. `chat list` names each chat's workspace, agent, state and last reply; `--session` takes the `session` it reports or the `handle` a launch returned.",
|
||||
"",
|
||||
"```text",
|
||||
"ORCA chat list --json",
|
||||
"ORCA chat list --state working --json",
|
||||
"ORCA chat read --session <session> --limit 10 --json",
|
||||
"ORCA chat send --session <session> --text \"<message>\" --json",
|
||||
"```",
|
||||
"",
|
||||
"- `chat read` returns messages, tool calls, errors, and approvals or questions; `pending: true` marks one waiting for the user.",
|
||||
"- `chat send` sends the text as the user's message. While the agent works, a host with a message queue holds it until the turn ends and reports `delivery: \"queued\"`.",
|
||||
"- A refused send was not delivered. Read the chat again before resending.",
|
||||
"- `chat send --wait` (or `chat wait`) returns when the chat settles, using `chat list` states: `settled: \"done\"`, or `\"blocked\"` on an approval or question, with the entries since the last user message; `settled: \"timeout\"` or `\"held\"` (queued message stopped or failed) exits 1. Pass `--timeout-ms`. Long or quoted text goes through `--text-file -` on stdin.",
|
||||
"- Paired hosts can `chat list` only; read, send and wait run on the host machine.",
|
||||
"- When relaying for a user from outside Orca (for example a voice or messaging assistant on the same machine), report from `chat list` and `chat read`, repeat an instruction back and get the user's confirmation before `chat send`, and send the user's words without adding instructions.",
|
||||
"",
|
||||
"<!-- host-capability: artifact-publishing -->",
|
||||
"",
|
||||
"## Artifacts",
|
||||
|
||||
@@ -1,206 +0,0 @@
|
||||
import type {
|
||||
AgentSessionHistoryPage,
|
||||
AgentSessionHistoryResult
|
||||
} from '../shared/agent-session/agent-session-wire'
|
||||
import type { AgentSessionWorkState } from '../shared/agent-session/agent-session-work-state'
|
||||
import { AGENT_SESSION_HISTORY_MAX_LIMIT } from '../shared/agent-session/agent-session-wire'
|
||||
import {
|
||||
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
|
||||
isUnattachedAgentSessionReadRefusal
|
||||
} from '../shared/agent-session/failures/structured-agent-session-read-refusal'
|
||||
import { structuredAgentSessionQueueSendsNext } from '../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { chatTranscript, formatChatRead, type ChatTranscriptEntry } from './chat-sessions'
|
||||
import type { RuntimeClient, RuntimeRpcSuccess } from './runtime-client'
|
||||
import { RuntimeClientError } from './runtime-client'
|
||||
|
||||
export const DEFAULT_READ_LIMIT = 20
|
||||
const WAIT_POLL_MS = 1000
|
||||
|
||||
export type ChatTranscript = {
|
||||
session: string
|
||||
entries: ChatTranscriptEntry[]
|
||||
/** Newest journal row read, so a later `--since` can continue from it. */
|
||||
cursor: AgentSessionHistoryPage['window']['newest']
|
||||
/** Older rows exist that this 200-row read did not reach, and they were needed. */
|
||||
truncated: boolean
|
||||
}
|
||||
/** The chat's own turn in `chat list` words (structuredAgentSessionLeadState), plus two wait-only outcomes. */
|
||||
export type ChatSettled = 'done' | 'blocked' | 'held' | 'timeout'
|
||||
|
||||
export async function readHistory(
|
||||
client: RuntimeClient,
|
||||
session: string,
|
||||
limit: number
|
||||
): Promise<RuntimeRpcSuccess<AgentSessionHistoryResult>> {
|
||||
return client
|
||||
.call<AgentSessionHistoryResult>('agentSession.history', {
|
||||
sessionId: session,
|
||||
direction: 'tail',
|
||||
limit
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
throw explainChatRefusal(error, session, 'read')
|
||||
})
|
||||
}
|
||||
|
||||
export async function readTranscript(
|
||||
client: RuntimeClient,
|
||||
session: string,
|
||||
limit?: number
|
||||
): Promise<RuntimeRpcSuccess<ChatTranscript>> {
|
||||
// Status frames and turn markers share the journal, so read the most rows a page allows.
|
||||
const response = await readHistory(client, session, AGENT_SESSION_HISTORY_MAX_LIMIT)
|
||||
const { page } = response.result
|
||||
const all = chatTranscript(page.items, page.actionablePromptIds)
|
||||
const entries = limit === undefined ? all : all.slice(-limit)
|
||||
const truncated = page.hasOlder && (limit === undefined || all.length < limit)
|
||||
return { ...response, result: { session, entries, cursor: page.window.newest, truncated } }
|
||||
}
|
||||
|
||||
/** Older hosts' history pages may omit `working`. */
|
||||
export type ChatWorkState = Omit<AgentSessionWorkState, 'working'> & { working?: boolean }
|
||||
|
||||
/** One command's reads of the facts a send or wait decides from. Hosts without
|
||||
* `agentSession.workState` answer from a history page for the rest of the command. */
|
||||
export function chatWorkStateReader(
|
||||
client: RuntimeClient,
|
||||
session: string
|
||||
): () => Promise<ChatWorkState> {
|
||||
let historyOnly = false
|
||||
return async () => {
|
||||
if (!historyOnly) {
|
||||
try {
|
||||
const response = await client.call<AgentSessionWorkState>('agentSession.workState', {
|
||||
sessionId: session
|
||||
})
|
||||
return response.result
|
||||
} catch (error) {
|
||||
if (!(error instanceof RuntimeClientError && error.code === 'method_not_found')) {
|
||||
throw explainChatRefusal(error, session, 'read')
|
||||
}
|
||||
historyOnly = true
|
||||
}
|
||||
}
|
||||
const { page } = (await readHistory(client, session, 1)).result
|
||||
return {
|
||||
...(page.working !== undefined ? { working: page.working } : {}),
|
||||
actionablePrompt: (page.actionablePromptIds?.length ?? 0) > 0,
|
||||
...(page.queuedMessages !== undefined
|
||||
? { queuedMessageIds: (page.queuedMessages ?? []).map((m) => m.messageId) }
|
||||
: {}),
|
||||
nextQueuedMessageId: page.nextQueuedMessageId ?? null,
|
||||
...(page.fence !== undefined ? { fence: page.fence } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function requireWorkingFlag(state: { working?: boolean }): void {
|
||||
if (state.working === undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
'This Orca host does not report when a chat is working, so it cannot wait. Update Orca on the host.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// Settled means no running turn or unanswered send, or a question/approval waiting for the user.
|
||||
export async function waitForChat(
|
||||
readWorkState: () => Promise<ChatWorkState>,
|
||||
timeoutMs: number | undefined,
|
||||
queuedMessageId?: string
|
||||
): Promise<ChatSettled> {
|
||||
const deadline = timeoutMs === undefined ? Infinity : Date.now() + timeoutMs
|
||||
for (;;) {
|
||||
const state = await readWorkState()
|
||||
requireWorkingFlag(state)
|
||||
if (state.actionablePrompt) {
|
||||
return 'blocked'
|
||||
}
|
||||
// Between turns the host names its next automatic send while working is briefly false.
|
||||
const sendsNext = structuredAgentSessionQueueSendsNext(
|
||||
state.nextQueuedMessageId,
|
||||
state.working === true
|
||||
)
|
||||
if (!state.working && !sendsNext) {
|
||||
// Still queued with nothing running or about to send: stopped, failed or held across a reopen.
|
||||
const held =
|
||||
queuedMessageId !== undefined && state.queuedMessageIds?.includes(queuedMessageId) === true
|
||||
return held ? 'held' : 'done'
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
return 'timeout'
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, WAIT_POLL_MS))
|
||||
}
|
||||
}
|
||||
|
||||
// After a wait, the turn's entries: everything after the last user message.
|
||||
export async function readSettledTurn(
|
||||
client: RuntimeClient,
|
||||
session: string,
|
||||
settled: ChatSettled
|
||||
): Promise<RuntimeRpcSuccess<ChatTranscript & { settled: ChatSettled }>> {
|
||||
if (settled === 'timeout' || settled === 'held') {
|
||||
// Chained commands such as `send --wait && ...` need a failing exit when the chat did not settle.
|
||||
process.exitCode = 1
|
||||
}
|
||||
const response = await readTranscript(client, session)
|
||||
const { entries, truncated } = response.result
|
||||
const lastUser = entries.findLastIndex((e) => e.kind === 'message' && e.role === 'user')
|
||||
// A held message never ran, so the last turn on the page is not its reply.
|
||||
const turn = settled === 'held' ? [] : entries.slice(lastUser + 1)
|
||||
return {
|
||||
...response,
|
||||
result: {
|
||||
...response.result,
|
||||
entries: turn,
|
||||
truncated: settled !== 'held' && truncated && lastUser === -1,
|
||||
settled
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function formatSettled(result: ChatTranscript & { settled: ChatSettled }): string {
|
||||
const status =
|
||||
result.settled === 'timeout'
|
||||
? 'Still working when the wait timed out.'
|
||||
: result.settled === 'held'
|
||||
? 'Your message is held in the queue (the chat was stopped or the send failed). Resume it in Orca.'
|
||||
: result.settled === 'blocked'
|
||||
? 'Blocked: waiting for you to answer an approval or question.'
|
||||
: 'Done.'
|
||||
return result.entries.length === 0 ? status : `${formatChatRead(result)}\n${status}`
|
||||
}
|
||||
|
||||
// The host answers with bare wire codes; say what they mean for this command.
|
||||
export function explainChatRefusal(
|
||||
error: unknown,
|
||||
sessionId: string,
|
||||
action: 'rename' | 'read' | 'send to'
|
||||
): unknown {
|
||||
if (!(error instanceof RuntimeClientError)) {
|
||||
return error
|
||||
}
|
||||
if (error.message === 'agent_session_identity_required') {
|
||||
return new RuntimeClientError(
|
||||
'agent_session_identity_required',
|
||||
`No chat with session id ${sessionId} on this host.`
|
||||
)
|
||||
}
|
||||
if (isUnattachedAgentSessionReadRefusal(error)) {
|
||||
return new RuntimeClientError(
|
||||
AGENT_SESSION_UNATTACHED_REFUSAL_CODE,
|
||||
`No open chat with session id ${sessionId} on this host. Find it with \`orca chat list\`.`
|
||||
)
|
||||
}
|
||||
if (
|
||||
error.message === 'structured_agent_session_unsupported' ||
|
||||
error.code === 'method_not_found'
|
||||
) {
|
||||
return new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
`This Orca host cannot ${action} chats from the CLI. Update Orca on that host, or check that it has chats turned on.`
|
||||
)
|
||||
}
|
||||
return error
|
||||
}
|
||||
@@ -1,175 +0,0 @@
|
||||
import { agentSessionPromptQuestions } from '../shared/agent-session/agent-session-question-answer'
|
||||
import { isActionableStructuredAgentSessionPrompt } from '../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { isRootAgentJournalItem } from '../shared/agent-session/journal/agent-session-journal-producer'
|
||||
import type { AgentJournalRenderItem } from '../shared/agent-session/journal/agent-session-journal-types'
|
||||
import type {
|
||||
RuntimeWorktreeAgentRow,
|
||||
RuntimeWorktreePsSummary
|
||||
} from '../shared/runtime-worktree-contracts'
|
||||
import { structuredAgentSessionTabId } from '../shared/agent-session/view/structured-agent-session-projection'
|
||||
import { RuntimeClientError } from './runtime-client'
|
||||
|
||||
const CHAT_HANDLE_PREFIX = structuredAgentSessionTabId('')
|
||||
|
||||
export type ChatSessionEntry = {
|
||||
session: string
|
||||
handle: string
|
||||
worktreeId: string
|
||||
worktree: string
|
||||
agentType: string | null
|
||||
state: RuntimeWorktreeAgentRow['state']
|
||||
title: string | null
|
||||
lastAssistantMessage: string | null
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export type ChatTranscriptEntry =
|
||||
| { kind: 'message'; role: string; text: string }
|
||||
| { kind: 'tool'; name: string; state: string }
|
||||
| { kind: 'approval' | 'question'; text: string; pending: boolean }
|
||||
| { kind: 'error'; text: string }
|
||||
|
||||
/** The session id a chat is addressed by, from its id, its handle, or a pane key that names it. */
|
||||
export function parseChatSessionSelector(value: string): string {
|
||||
const withoutHandle = value.startsWith(CHAT_HANDLE_PREFIX)
|
||||
? value.slice(CHAT_HANDLE_PREFIX.length)
|
||||
: value
|
||||
// A pane key is the chat's handle and its leaf: "<handle>:<leaf>".
|
||||
const session = withoutHandle.split(':')[0]?.trim() ?? ''
|
||||
if (session.length === 0) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'--session needs a chat session id or handle; run `orca chat list` to find one.'
|
||||
)
|
||||
}
|
||||
return session
|
||||
}
|
||||
|
||||
/** The top-level chats in a worktree summary. Terminal agents and subagents are left out:
|
||||
* terminals are read with `orca terminal`, and a subagent is reached through its parent chat. */
|
||||
export function listChatSessions(
|
||||
worktrees: readonly RuntimeWorktreePsSummary[]
|
||||
): ChatSessionEntry[] {
|
||||
return worktrees.flatMap((worktree) =>
|
||||
worktree.agents
|
||||
.filter(
|
||||
(agent) => agent.parentPaneKey === null && agent.paneKey.startsWith(CHAT_HANDLE_PREFIX)
|
||||
)
|
||||
.map((agent) => {
|
||||
const session = parseChatSessionSelector(agent.paneKey)
|
||||
return {
|
||||
session,
|
||||
handle: structuredAgentSessionTabId(session),
|
||||
worktreeId: worktree.worktreeId,
|
||||
worktree: worktree.displayName,
|
||||
agentType: agent.agentType,
|
||||
state: agent.state,
|
||||
title: agent.displayName ?? agent.taskTitle,
|
||||
lastAssistantMessage: agent.lastAssistantMessage,
|
||||
updatedAt: agent.updatedAt
|
||||
}
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
function messageText(item: AgentJournalRenderItem): string {
|
||||
if (item.body.kind !== 'message') {
|
||||
return ''
|
||||
}
|
||||
return item.body.blocks
|
||||
.map((block) =>
|
||||
block.type === 'text' ? block.text : block.type === 'image-ref' ? '[image]' : ''
|
||||
)
|
||||
.filter((text) => text.length > 0)
|
||||
.join('\n')
|
||||
.trim()
|
||||
}
|
||||
|
||||
/** The conversation as a reader follows it: messages, the tools the agent ran, and the
|
||||
* approvals and questions it raised. Provider status frames and turn markers are left out. */
|
||||
export function chatTranscript(
|
||||
items: readonly AgentJournalRenderItem[],
|
||||
actionablePromptIds?: readonly string[]
|
||||
): ChatTranscriptEntry[] {
|
||||
// An ended agent's unanswered prompts stay pending in the journal but can no longer be answered.
|
||||
const waiting = (item: AgentJournalRenderItem, state: string): boolean =>
|
||||
state === 'pending' &&
|
||||
isActionableStructuredAgentSessionPrompt(item.itemId, actionablePromptIds)
|
||||
const entries: ChatTranscriptEntry[] = []
|
||||
for (const item of items) {
|
||||
// Subagents share the journal; their rows belong to their own section, not the chat's turn.
|
||||
if (!isRootAgentJournalItem(item)) {
|
||||
continue
|
||||
}
|
||||
const body = item.body
|
||||
if (body.kind === 'message') {
|
||||
const text = messageText(item)
|
||||
// Reasoning is the model's scratch work, folded away in the app too.
|
||||
if (text.length > 0 && body.role !== 'reasoning') {
|
||||
entries.push({ kind: 'message', role: body.role, text })
|
||||
}
|
||||
} else if (body.kind === 'status' && body.tone === 'error') {
|
||||
// Start failures and dead agents land as error status rows; without them a wait reads "Done.".
|
||||
entries.push({ kind: 'error', text: String(body.text) })
|
||||
} else if (body.kind === 'tool-call') {
|
||||
entries.push({ kind: 'tool', name: body.name, state: body.state })
|
||||
} else if (body.kind === 'approval') {
|
||||
entries.push({
|
||||
kind: 'approval',
|
||||
text: body.title,
|
||||
pending: waiting(item, body.resolution.state)
|
||||
})
|
||||
} else if (body.kind === 'question') {
|
||||
entries.push({
|
||||
kind: 'question',
|
||||
// Grouped prompts keep their real questions in `questions`; `question` is then a heading.
|
||||
text: agentSessionPromptQuestions(body)
|
||||
.map((q) => q.question)
|
||||
.join('\n'),
|
||||
pending: waiting(item, body.resolution.state)
|
||||
})
|
||||
}
|
||||
}
|
||||
return entries
|
||||
}
|
||||
|
||||
export function formatChatList(result: { chats: ChatSessionEntry[] }): string {
|
||||
if (result.chats.length === 0) {
|
||||
return 'No chats.'
|
||||
}
|
||||
return result.chats
|
||||
.map((chat) =>
|
||||
[
|
||||
`${chat.worktree} · ${chat.agentType ?? 'agent'} · ${chat.state}`,
|
||||
` session: ${chat.session}`,
|
||||
...(chat.title ? [` title: ${chat.title}`] : []),
|
||||
...(chat.lastAssistantMessage
|
||||
? [` last reply: ${chat.lastAssistantMessage.replace(/\s+/g, ' ').slice(0, 200)}`]
|
||||
: [])
|
||||
].join('\n')
|
||||
)
|
||||
.join('\n\n')
|
||||
}
|
||||
|
||||
export function formatChatRead(result: {
|
||||
session: string
|
||||
entries: ChatTranscriptEntry[]
|
||||
}): string {
|
||||
if (result.entries.length === 0) {
|
||||
return `No messages in ${result.session}.`
|
||||
}
|
||||
return result.entries
|
||||
.map((entry) => {
|
||||
if (entry.kind === 'message') {
|
||||
return `${entry.role}: ${entry.text}`
|
||||
}
|
||||
if (entry.kind === 'error') {
|
||||
return `[error] ${entry.text}`
|
||||
}
|
||||
if (entry.kind === 'tool') {
|
||||
return `[tool ${entry.name}: ${entry.state}]`
|
||||
}
|
||||
return `[${entry.kind}${entry.pending ? ', waiting for you' : ''}] ${entry.text}`
|
||||
})
|
||||
.join('\n')
|
||||
}
|
||||
@@ -2,22 +2,7 @@
|
||||
const FILE_OPEN_FOCUS_HELP =
|
||||
"--focus Bring the user to the file (switches Orca's window to its worktree)"
|
||||
|
||||
const CHAT_SESSION_HELP =
|
||||
'--session <id> Chat session id or handle from chat list or agent launch'
|
||||
|
||||
const COMMAND_SCOPED_FLAG_HELP: Record<string, Record<string, string>> = {
|
||||
'chat rename': {
|
||||
session: '--session <id> Chat session id from chat list or agent launch'
|
||||
},
|
||||
'chat list': {
|
||||
state: '--state <state> Only chats in this state: working, blocked, waiting or done'
|
||||
},
|
||||
'chat read': { session: CHAT_SESSION_HELP },
|
||||
'chat send': {
|
||||
session: CHAT_SESSION_HELP,
|
||||
wait: '--wait Wait until the chat finishes or needs your answer'
|
||||
},
|
||||
'chat wait': { session: CHAT_SESSION_HELP },
|
||||
'extension reload': {
|
||||
'extension-id':
|
||||
'--extension-id <id> Installed unpacked extension ID; also accepted positionally',
|
||||
|
||||
@@ -36,7 +36,6 @@ export const FLAG_HELP_TEXT: Record<string, string> = {
|
||||
interrupt: '--interrupt Send as an interrupt-style input when supported',
|
||||
'keep-open': '--keep-open Keep the worker open after it finishes',
|
||||
'spec-file': '--spec-file <path|-> Read the spec from a file or stdin',
|
||||
'text-file': '--text-file <path|-> Read the text from a file or stdin',
|
||||
id: '--id <id> Identifier for a target item or permission',
|
||||
issue: '--issue <number|null> Linked GitHub issue number',
|
||||
'gitlab-issue':
|
||||
|
||||
@@ -207,7 +207,7 @@ export const HANDLER_GROUPS: readonly HandlerGroup[] = [
|
||||
},
|
||||
{
|
||||
name: 'chat',
|
||||
keys: ['chat rename', 'chat list', 'chat read', 'chat send', 'chat wait'],
|
||||
keys: ['chat rename'],
|
||||
load: async () => (await import('./handlers/chat.js')).CHAT_HANDLERS
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,166 +1,7 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { RuntimeClient } from '../runtime-client'
|
||||
import { CHAT_HANDLERS } from './chat'
|
||||
|
||||
const SESSION = 'codex_8eb631ab_59c5_41e4_8672_01cfe0a6fd5f'
|
||||
|
||||
function ok(result: unknown) {
|
||||
return { id: 'req', ok: true, result, _meta: { runtimeId: 'runtime-1' } }
|
||||
}
|
||||
|
||||
function historyPage(
|
||||
items: unknown[],
|
||||
fence: number | undefined = 3,
|
||||
pageOverrides: Record<string, unknown> = {}
|
||||
) {
|
||||
return ok({
|
||||
ok: true,
|
||||
page: {
|
||||
sessionId: SESSION,
|
||||
epoch: 'e',
|
||||
fence,
|
||||
direction: 'tail',
|
||||
items,
|
||||
removedItemIds: [],
|
||||
submissions: [],
|
||||
window: {
|
||||
oldest: null,
|
||||
newest: { epoch: 'e', sequence: 9 },
|
||||
nextCursor: { epoch: 'e', sequence: 9 }
|
||||
},
|
||||
...pageOverrides
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function workState(fields: Record<string, unknown>) {
|
||||
return ok({ working: false, actionablePrompt: false, ...fields })
|
||||
}
|
||||
|
||||
function item(body: unknown) {
|
||||
return { itemId: 'i', revision: 1, sequence: 1, observedAt: 1, body }
|
||||
}
|
||||
|
||||
function fakeClient(
|
||||
responses: unknown[],
|
||||
capabilities: string[] = [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY]
|
||||
): RuntimeClient & { call: ReturnType<typeof vi.fn> } {
|
||||
const client = new RuntimeClient('/tmp/orca-chat-test', 60_000, null, null)
|
||||
const call = vi.fn()
|
||||
for (const response of responses) {
|
||||
call.mockResolvedValueOnce(response)
|
||||
}
|
||||
vi.spyOn(client, 'call').mockImplementation(call)
|
||||
vi.spyOn(client, 'getCliStatus').mockResolvedValue({
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: {
|
||||
app: { running: true, pid: 123 },
|
||||
runtime: { state: 'ready', reachable: true, runtimeId: 'runtime-1', capabilities },
|
||||
graph: { state: 'ready' }
|
||||
},
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
})
|
||||
return Object.assign(client, { call })
|
||||
}
|
||||
|
||||
async function run(
|
||||
command: string,
|
||||
flags: Record<string, string | boolean>,
|
||||
client: RuntimeClient
|
||||
) {
|
||||
const logs: string[] = []
|
||||
const spy = vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line))
|
||||
try {
|
||||
await CHAT_HANDLERS[command]!({
|
||||
flags: new Map(Object.entries(flags)),
|
||||
client,
|
||||
cwd: '/tmp',
|
||||
json: true
|
||||
})
|
||||
} finally {
|
||||
spy.mockRestore()
|
||||
}
|
||||
return JSON.parse(logs.join('\n')).result
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe('chat send', () => {
|
||||
it('fences a queued message to the chat it read', async () => {
|
||||
const client = fakeClient([
|
||||
workState({ fence: 7 }),
|
||||
ok({
|
||||
ok: true,
|
||||
replayed: false,
|
||||
fence: 7,
|
||||
cursor: { epoch: 'e', sequence: 2 },
|
||||
value: {
|
||||
clientMessageId: 'm-1',
|
||||
queued: { messageId: 'q-1', position: 1, state: 'waiting' }
|
||||
}
|
||||
})
|
||||
])
|
||||
const result = await run('chat send', { session: SESSION, text: 'Run the tests' }, client)
|
||||
const params = client.call.mock.calls[1]![1]
|
||||
expect(client.call.mock.calls[1]![0]).toBe('agentSession.send')
|
||||
expect(params).toMatchObject({
|
||||
envelope: { sessionId: SESSION, expectedRuntimeFence: 7 },
|
||||
delivery: 'queue-if-active',
|
||||
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Run the tests' }] }
|
||||
})
|
||||
expect(result).toEqual({
|
||||
session: SESSION,
|
||||
delivery: 'queued',
|
||||
clientMessageId: 'm-1',
|
||||
queuePosition: 1
|
||||
})
|
||||
})
|
||||
|
||||
it('with --wait, waits for its queued message to run and returns that turn', async () => {
|
||||
vi.useFakeTimers()
|
||||
const client = fakeClient([
|
||||
workState({ fence: 7, working: true }),
|
||||
ok({
|
||||
ok: true,
|
||||
replayed: false,
|
||||
fence: 7,
|
||||
cursor: { epoch: 'e', sequence: 2 },
|
||||
value: {
|
||||
clientMessageId: 'm-1',
|
||||
queued: { messageId: 'q-1', position: 1, state: 'waiting' }
|
||||
}
|
||||
}),
|
||||
// The earlier turn ended, but the queued message has not been handed to the agent yet.
|
||||
workState({ fence: 7, queuedMessageIds: ['q-1'], nextQueuedMessageId: 'q-1' }),
|
||||
workState({ fence: 7, working: true, queuedMessageIds: [] }),
|
||||
workState({ fence: 7, queuedMessageIds: [] }),
|
||||
historyPage([
|
||||
item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier' }] }),
|
||||
item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Old reply' }] }),
|
||||
item({ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Run the tests' }] }),
|
||||
item({ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'All pass' }] })
|
||||
])
|
||||
])
|
||||
const pending = run(
|
||||
'chat send',
|
||||
{ session: SESSION, text: 'Run the tests', wait: true },
|
||||
client
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
const result = await pending
|
||||
expect(result).toMatchObject({
|
||||
delivery: 'queued',
|
||||
settled: 'done',
|
||||
entries: [{ kind: 'message', role: 'assistant', text: 'All pass' }]
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function chatClient(isRemote: boolean): { client: RuntimeClient; call: ReturnType<typeof vi.fn> } {
|
||||
const client = new RuntimeClient('/tmp/orca-chat-test', 60_000, null, null)
|
||||
vi.spyOn(client, 'isRemote', 'get').mockReturnValue(isRemote)
|
||||
|
||||
+26
-165
@@ -1,64 +1,11 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type {
|
||||
AgentSessionMutationResult,
|
||||
AgentSessionSendResult
|
||||
} from '../../shared/agent-session/agent-session-wire'
|
||||
import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import type {
|
||||
RuntimeWorktreePsResult,
|
||||
RuntimeWorktreeRecord
|
||||
} from '../../shared/runtime-worktree-contracts'
|
||||
import { createStructuredAgentSessionOperationId } from '../../shared/agent-session/lifecycle/structured-agent-session-mutation'
|
||||
import {
|
||||
structuredAgentSessionMessageSendMutation,
|
||||
structuredAgentSessionSendBody
|
||||
} from '../../shared/agent-session/requests/structured-agent-session-send-mutation'
|
||||
import { AGENT_STATUS_STATES } from '../../shared/agent-status/contracts/agent-status-types'
|
||||
import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env'
|
||||
import {
|
||||
DEFAULT_READ_LIMIT,
|
||||
chatWorkStateReader,
|
||||
explainChatRefusal,
|
||||
formatSettled,
|
||||
readSettledTurn,
|
||||
readTranscript,
|
||||
requireWorkingFlag,
|
||||
waitForChat
|
||||
} from '../chat-history'
|
||||
import {
|
||||
formatChatList,
|
||||
formatChatRead,
|
||||
listChatSessions,
|
||||
parseChatSessionSelector
|
||||
} from '../chat-sessions'
|
||||
import { readTextOrFileFlag } from '../command-body-input'
|
||||
import type { CommandHandler } from '../dispatch'
|
||||
import {
|
||||
getOptionalPositiveIntegerFlag,
|
||||
getOptionalStringFlag,
|
||||
getPresentStringFlag,
|
||||
getRequiredStringFlag
|
||||
} from '../flags'
|
||||
import { getPresentStringFlag, getRequiredStringFlag } from '../flags'
|
||||
import { printResult } from '../format'
|
||||
import { getOptionalWorktreeSelector } from '../selectors'
|
||||
import type { RuntimeClient } from '../runtime-client'
|
||||
import { RuntimeClientError } from '../runtime-client'
|
||||
|
||||
const MAX_READ_LIMIT = 100
|
||||
import { readInjectedAgentSessionId } from '../../shared/agent-session/lifecycle/agent-session-caller-env'
|
||||
|
||||
type ChatRenameResult = { name: string | null; applied: boolean }
|
||||
|
||||
// Paired CLIs lack the host's chat read/send capability; refuse before the host does with a bare code.
|
||||
function readSession(flags: Map<string, string | boolean>, client: RuntimeClient): string {
|
||||
if (client.isRemote) {
|
||||
throw new RuntimeClientError(
|
||||
'runtime_unsupported',
|
||||
'Reading and messaging chats on a paired host is not supported yet. Run this on the host machine.'
|
||||
)
|
||||
}
|
||||
return parseChatSessionSelector(getRequiredStringFlag(flags, 'session'))
|
||||
}
|
||||
|
||||
export const CHAT_HANDLERS: Record<string, CommandHandler> = {
|
||||
'chat rename': async ({ flags, client, json }) => {
|
||||
const name = getRequiredStringFlag(flags, 'name')
|
||||
@@ -77,120 +24,34 @@ export const CHAT_HANDLERS: Record<string, CommandHandler> = {
|
||||
const result = await client
|
||||
.call<ChatRenameResult>('agentSession.rename', { sessionId, name })
|
||||
.catch((error: unknown) => {
|
||||
throw explainChatRefusal(error, sessionId, 'rename')
|
||||
throw explainRenameRefusal(error, sessionId)
|
||||
})
|
||||
if (!result.result.applied) {
|
||||
throw new RuntimeClientError('invalid_argument', 'Not renamed: the name has no visible text.')
|
||||
}
|
||||
printResult(result, json, (value) => `Renamed chat to "${value.name}".`)
|
||||
},
|
||||
'chat list': async ({ flags, client, cwd, json }) => {
|
||||
const state = getOptionalStringFlag(flags, 'state')
|
||||
if (state !== undefined && !AGENT_STATUS_STATES.some((known) => known === state)) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
`--state must be one of: ${AGENT_STATUS_STATES.join(', ')}.`
|
||||
)
|
||||
}
|
||||
const selector = await getOptionalWorktreeSelector(flags, 'worktree', cwd, client)
|
||||
const shown = selector
|
||||
? (
|
||||
await client.call<{ worktree: RuntimeWorktreeRecord }>('worktree.show', {
|
||||
worktree: selector
|
||||
})
|
||||
).result.worktree
|
||||
: undefined
|
||||
const result = await client.call<RuntimeWorktreePsResult>('worktree.ps', {})
|
||||
// A local and an SSH copy can share an id; the host tells them apart when both name one.
|
||||
const worktrees = result.result.worktrees.filter(
|
||||
(w) =>
|
||||
!shown ||
|
||||
(w.worktreeId === shown.id &&
|
||||
(w.hostId === undefined || shown.hostId === undefined || w.hostId === shown.hostId))
|
||||
)
|
||||
const chats = listChatSessions(worktrees).filter((chat) => !state || chat.state === state)
|
||||
printResult({ ...result, result: { chats } }, json, formatChatList)
|
||||
},
|
||||
'chat read': async ({ flags, client, json }) => {
|
||||
const session = readSession(flags, client)
|
||||
const limit = getOptionalPositiveIntegerFlag(flags, 'limit') ?? DEFAULT_READ_LIMIT
|
||||
if (limit > MAX_READ_LIMIT) {
|
||||
throw new RuntimeClientError('invalid_argument', `--limit must be at most ${MAX_READ_LIMIT}.`)
|
||||
}
|
||||
printResult(await readTranscript(client, session, limit), json, formatChatRead)
|
||||
},
|
||||
'chat wait': async ({ flags, client, json }) => {
|
||||
const session = readSession(flags, client)
|
||||
const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms')
|
||||
const settled = await waitForChat(chatWorkStateReader(client, session), timeoutMs)
|
||||
printResult(await readSettledTurn(client, session, settled), json, formatSettled)
|
||||
},
|
||||
'chat send': async ({ flags, client, cwd, json }) => {
|
||||
const session = readSession(flags, client)
|
||||
const text = (await readTextOrFileFlag(flags, cwd, 'text', true)) ?? ''
|
||||
if (text.trim().length === 0) {
|
||||
throw new RuntimeClientError('invalid_argument', 'The message must not be empty.')
|
||||
}
|
||||
const wait = flags.has('wait')
|
||||
const timeoutMs = getOptionalPositiveIntegerFlag(flags, 'timeout-ms')
|
||||
const status = await client.getCliStatus()
|
||||
if (!status.result.runtime.reachable) {
|
||||
throw new RuntimeClientError(
|
||||
'runtime_unavailable',
|
||||
'Orca could not reach the execution host, so nothing was sent. Retry once it is reachable.'
|
||||
)
|
||||
}
|
||||
// A working chat holds a queued message until its turn ends; older hosts get an ordinary send.
|
||||
const queue =
|
||||
status.result.runtime.capabilities?.includes(
|
||||
AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY
|
||||
) === true
|
||||
// The send is fenced to the session's current runtime, so a restarted chat refuses it.
|
||||
const readWorkState = chatWorkStateReader(client, session)
|
||||
const state = await readWorkState()
|
||||
if (wait) {
|
||||
requireWorkingFlag(state)
|
||||
}
|
||||
const { fence } = state
|
||||
if (fence === undefined) {
|
||||
throw new RuntimeClientError(
|
||||
'agent_session_not_running',
|
||||
`Chat ${session} has no running session on this host, so nothing was sent. Open it in Orca and retry.`
|
||||
)
|
||||
}
|
||||
const mutation = structuredAgentSessionMessageSendMutation({
|
||||
sessionId: session,
|
||||
clientOperationId: createStructuredAgentSessionOperationId(randomUUID),
|
||||
expectedRuntimeFence: fence,
|
||||
body: structuredAgentSessionSendBody(text, []),
|
||||
...(queue ? { delivery: 'queue-if-active' as const } : {})
|
||||
})
|
||||
const result = await client.call<AgentSessionMutationResult<AgentSessionSendResult>>(
|
||||
'agentSession.send',
|
||||
mutation
|
||||
)
|
||||
if (!result.result.ok) {
|
||||
const { code, message } = result.result.refusal
|
||||
throw explainChatRefusal(new RuntimeClientError(code, message), session, 'send to')
|
||||
}
|
||||
const value = result.result.value
|
||||
const sent = {
|
||||
session,
|
||||
delivery: 'queued' in value ? ('queued' as const) : ('submitted' as const),
|
||||
clientMessageId: value.clientMessageId,
|
||||
...('queued' in value ? { queuePosition: value.queued.position } : {})
|
||||
}
|
||||
if (!wait) {
|
||||
printResult({ ...result, result: sent }, json, (r) =>
|
||||
r.delivery === 'queued'
|
||||
? `Queued for ${r.session}; it is sent when the current turn ends.`
|
||||
: `Sent to ${r.session}.`
|
||||
)
|
||||
return
|
||||
}
|
||||
const queuedId = 'queued' in value ? value.queued.messageId : undefined
|
||||
const settled = await waitForChat(readWorkState, timeoutMs, queuedId)
|
||||
const turn = await readSettledTurn(client, session, settled)
|
||||
printResult({ ...turn, result: { ...sent, ...turn.result } }, json, formatSettled)
|
||||
}
|
||||
}
|
||||
|
||||
// The host answers with bare wire codes; say what they mean for this command.
|
||||
function explainRenameRefusal(error: unknown, sessionId: string): unknown {
|
||||
if (!(error instanceof RuntimeClientError)) {
|
||||
return error
|
||||
}
|
||||
if (error.message === 'agent_session_identity_required') {
|
||||
return new RuntimeClientError(
|
||||
'agent_session_identity_required',
|
||||
`No chat with session id ${sessionId} on this host.`
|
||||
)
|
||||
}
|
||||
if (
|
||||
error.message === 'structured_agent_session_unsupported' ||
|
||||
error.code === 'method_not_found'
|
||||
) {
|
||||
return new RuntimeClientError(
|
||||
'incompatible_runtime',
|
||||
'This Orca host cannot rename chats from the CLI. Update Orca on that host, or check that it has chats turned on.'
|
||||
)
|
||||
}
|
||||
return error
|
||||
}
|
||||
|
||||
@@ -121,10 +121,6 @@ export const ROOT_HELP_TEXT_PRIMARY = [
|
||||
' agent launch Start an agent in a worktree, as a chat or terminal per your settings',
|
||||
'',
|
||||
'Chats:',
|
||||
' chat list List agent chats with their workspace, state and last reply',
|
||||
' chat read Read the latest messages of an agent chat',
|
||||
' chat send Send a message to an agent chat',
|
||||
' chat wait Wait until an agent chat finishes or needs your answer',
|
||||
' chat rename Rename a chat tab',
|
||||
'',
|
||||
'Files:',
|
||||
|
||||
@@ -15,57 +15,5 @@ export const CHAT_COMMAND_SPECS: CommandSpec[] = [
|
||||
'orca chat rename --name "Migrate auth to OAuth"',
|
||||
'orca chat rename --session <sessionId> --name "Release notes" --json'
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ['chat', 'list'],
|
||||
summary: 'List agent chats with their workspace, state and last reply',
|
||||
usage: 'orca chat list [--worktree <selector>] [--state <state>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'worktree', 'state'],
|
||||
notes: [
|
||||
'Lists the top-level chats Orca shows as agent tabs. Terminal agents are read with `orca terminal`.',
|
||||
'--state keeps chats in one state: working, blocked, waiting or done.'
|
||||
],
|
||||
examples: ['orca chat list --json', 'orca chat list --state working']
|
||||
},
|
||||
{
|
||||
path: ['chat', 'read'],
|
||||
summary: 'Read the latest messages of an agent chat',
|
||||
usage: 'orca chat read --session <id-or-handle> [--limit <n>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'session', 'limit'],
|
||||
notes: [
|
||||
'--session takes the session id or handle from `orca chat list` or `orca agent launch`.',
|
||||
'--limit is the number of entries shown (messages, tool calls, approvals and questions); the default is 20 and the maximum 100.',
|
||||
'Approvals and questions waiting for an answer are marked "waiting for you".'
|
||||
],
|
||||
examples: ['orca chat read --session codex_1234 --limit 10']
|
||||
},
|
||||
{
|
||||
path: ['chat', 'send'],
|
||||
summary: 'Send a message to an agent chat',
|
||||
usage:
|
||||
'orca chat send --session <id-or-handle> (--text <text> | --text-file <path|->) [--wait] [--timeout-ms <ms>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'session', 'text', 'text-file', 'wait', 'timeout-ms'],
|
||||
notes: [
|
||||
'Sends the text as your message, as if typed in the chat. --text-file - reads it from stdin.',
|
||||
'While the agent is working, hosts with a message queue hold the message until the turn ends; the result says "queued".',
|
||||
'--wait returns once the chat finishes or waits for your answer, with what it did since your message. It exits 1 when the wait times out or the message is held in a stopped queue.',
|
||||
'A chat that restarted since it was read refuses the send; read it again and resend.'
|
||||
],
|
||||
examples: [
|
||||
'orca chat send --session codex_1234 --text "Run the tests, then summarize failures"',
|
||||
'orca chat send --session codex_1234 --text "Run the tests" --wait --timeout-ms 600000 --json',
|
||||
'cat notes.md | orca chat send --session codex_1234 --text-file -'
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ['chat', 'wait'],
|
||||
summary: 'Wait until an agent chat finishes or needs your answer',
|
||||
usage: 'orca chat wait --session <id-or-handle> [--timeout-ms <ms>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'session', 'timeout-ms'],
|
||||
notes: [
|
||||
'Settles on the chat\'s own turn, in `chat list` words: "done", or "blocked" on an approval or question. Background agents it started can still show as working or waiting in `chat list`. "held" and "timeout" exit 1.',
|
||||
'Prints what the chat did since the last user message. A wait that times out exits 1.'
|
||||
],
|
||||
examples: ['orca chat wait --session codex_1234 --timeout-ms 600000 --json']
|
||||
}
|
||||
]
|
||||
|
||||
-64
@@ -1,64 +0,0 @@
|
||||
import { mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, beforeEach, expect, it } from 'vitest'
|
||||
import { createProgramStatusProjector } from '../../../../../shared/program-status/agent-status-projector'
|
||||
import { AgentHookServer } from '../../agent-hook-server'
|
||||
import { buildBody, PANE, postHookEvent } from '../server.test-fixtures'
|
||||
|
||||
const SESSION = 'sess_11111111-2222-4333-8444-555555555555'
|
||||
|
||||
// Shape written by kiro-cli 3.1.0's TUI, which reports under its binary name.
|
||||
const kiroOsc = (state: string): string => `\x1b]7501;state=${state}:app=kiro-cli\x07`
|
||||
|
||||
let dir: string
|
||||
let server: AgentHookServer
|
||||
let projector: ReturnType<typeof createProgramStatusProjector>
|
||||
|
||||
beforeEach(async () => {
|
||||
dir = mkdtempSync(join(tmpdir(), 'orca-kiro-program-status-'))
|
||||
server = new AgentHookServer()
|
||||
await server.start({ env: 'production', userDataPath: dir })
|
||||
projector = createProgramStatusProjector()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
server.stop()
|
||||
rmSync(dir, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
async function kiroHook(hookEventName: string, payload: Record<string, unknown> = {}) {
|
||||
const response = await postHookEvent(
|
||||
server,
|
||||
buildBody({ session_id: SESSION, hook_event_name: hookEventName, cwd: '/repo', ...payload }),
|
||||
'/hook/kiro'
|
||||
)
|
||||
expect(response.status).toBe(204)
|
||||
}
|
||||
|
||||
function kiroReports(state: string): void {
|
||||
for (const { payload } of projector.process(kiroOsc(state)).payloads) {
|
||||
server.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
connectionId: null,
|
||||
fromProgramStatus: true,
|
||||
payload
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function recordedRow() {
|
||||
const row = server.getStatusSnapshot()[0]
|
||||
return { agentType: row?.agentType, sessionId: row?.providerSession?.id }
|
||||
}
|
||||
|
||||
it('keeps the Kiro session through a turn that Kiro also reports over OSC 7501', async () => {
|
||||
kiroReports('working')
|
||||
await kiroHook('UserPromptSubmit', { prompt: 'hi' })
|
||||
await kiroHook('Stop')
|
||||
kiroReports('done')
|
||||
|
||||
expect(recordedRow()).toEqual({ agentType: 'kiro', sessionId: SESSION })
|
||||
})
|
||||
+74
-83
@@ -34,95 +34,86 @@ function previousRoot(children: number): AgentHookEventPayload {
|
||||
}
|
||||
}
|
||||
|
||||
it.each([10, 100])(
|
||||
'retires %i foreign-session children at a cached startup boundary',
|
||||
(children) => {
|
||||
const desktop = new AgentHookServer()
|
||||
desktop.beginRemoteRelaySession('wsl:Ubuntu')
|
||||
desktop.ingestRemote(previousRoot(children), 'wsl:Ubuntu')
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toHaveLength(children)
|
||||
if (children === 100) {
|
||||
desktop.beginRemoteRelaySession('wsl:Ubuntu')
|
||||
}
|
||||
const incoming: AgentHookEventPayload = {
|
||||
...previousRoot(0),
|
||||
toolAgentId: undefined,
|
||||
hookEventName: 'SessionStart',
|
||||
providerSession: { key: 'session_id', id: 'new-root' },
|
||||
payload: {
|
||||
agentType: 'codex',
|
||||
state: 'done',
|
||||
sessionBoundary: true,
|
||||
prompt: 'new context',
|
||||
model: 'new-model',
|
||||
mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 2000 }
|
||||
}
|
||||
}
|
||||
desktop.ingestRemote(
|
||||
buildCachedPaneReplayEnvelope({ event: incoming, meta: { source: 'codex' } }),
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0]).toMatchObject({
|
||||
it('retires foreign-session children at a cached startup boundary', () => {
|
||||
const children = 100
|
||||
const desktop = new AgentHookServer()
|
||||
desktop.beginRemoteRelaySession('wsl:Ubuntu')
|
||||
desktop.ingestRemote(previousRoot(children), 'wsl:Ubuntu')
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toHaveLength(children)
|
||||
desktop.beginRemoteRelaySession('wsl:Ubuntu')
|
||||
const incoming: AgentHookEventPayload = {
|
||||
...previousRoot(0),
|
||||
toolAgentId: undefined,
|
||||
hookEventName: 'SessionStart',
|
||||
providerSession: { key: 'session_id', id: 'new-root' },
|
||||
payload: {
|
||||
agentType: 'codex',
|
||||
state: 'done',
|
||||
restoredUnconfirmed: true,
|
||||
providerSession: { id: 'new-root' },
|
||||
sessionBoundary: true,
|
||||
prompt: 'new context',
|
||||
model: 'new-model',
|
||||
mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 2000 }
|
||||
})
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined()
|
||||
expect(desktop._getStateForTests().codexSubagentRosterByPaneKey.get(PANE)?.size).toBe(0)
|
||||
desktop.ingestRemote({ ...incoming, hookEventName: undefined }, 'wsl:Ubuntu')
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined()
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['previous', 'incoming'] as const)(
|
||||
'preserves live context when the %s session ID is missing',
|
||||
(missing) => {
|
||||
const desktop = new AgentHookServer()
|
||||
const previous = previousRoot(1)
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(1_000)
|
||||
try {
|
||||
desktop.ingestRemote(
|
||||
{
|
||||
...previous,
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
toolAgentId: undefined,
|
||||
hasExplicitPrompt: true,
|
||||
providerSession: missing === 'previous' ? undefined : previous.providerSession,
|
||||
payload: { ...previous.payload, mainAgent: { state: 'working', stateStartedAt: 1000 } }
|
||||
},
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBe(1_000)
|
||||
vi.setSystemTime(3_000)
|
||||
desktop.ingestRemote(
|
||||
{
|
||||
...previous,
|
||||
toolAgentId: undefined,
|
||||
hookEventName: 'SessionStart',
|
||||
providerSession:
|
||||
missing === 'incoming' ? undefined : { key: 'session_id', id: 'new-root' },
|
||||
payload: { agentType: 'codex', state: 'working', prompt: '' }
|
||||
},
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'working',
|
||||
prompt: 'old task',
|
||||
model: 'old-model',
|
||||
mainAgent: { state: 'working', stateStartedAt: 1000 },
|
||||
subagents: [{ id: 'old-0', state: 'working' }],
|
||||
turnStartedAt: 1_000
|
||||
})
|
||||
} finally {
|
||||
desktop.stop()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
}
|
||||
)
|
||||
desktop.ingestRemote(
|
||||
buildCachedPaneReplayEnvelope({ event: incoming, meta: { source: 'codex' } }),
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'done',
|
||||
restoredUnconfirmed: true,
|
||||
providerSession: { id: 'new-root' },
|
||||
prompt: 'new context',
|
||||
model: 'new-model',
|
||||
mainAgent: { state: 'done', outcome: 'cancellation', stateStartedAt: 2000 }
|
||||
})
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined()
|
||||
desktop.ingestRemote({ ...incoming, hookEventName: undefined }, 'wsl:Ubuntu')
|
||||
expect(desktop.getStatusSnapshot()[0].subagents).toBeUndefined()
|
||||
})
|
||||
|
||||
it('preserves live context when the incoming session ID is missing', () => {
|
||||
const desktop = new AgentHookServer()
|
||||
const previous = previousRoot(1)
|
||||
vi.useFakeTimers({ toFake: ['Date'] })
|
||||
vi.setSystemTime(1_000)
|
||||
try {
|
||||
desktop.ingestRemote(
|
||||
{
|
||||
...previous,
|
||||
hookEventName: 'UserPromptSubmit',
|
||||
toolAgentId: undefined,
|
||||
hasExplicitPrompt: true,
|
||||
providerSession: previous.providerSession,
|
||||
payload: { ...previous.payload, mainAgent: { state: 'working', stateStartedAt: 1000 } }
|
||||
},
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0].turnStartedAt).toBe(1_000)
|
||||
vi.setSystemTime(3_000)
|
||||
desktop.ingestRemote(
|
||||
{
|
||||
...previous,
|
||||
toolAgentId: undefined,
|
||||
hookEventName: 'SessionStart',
|
||||
providerSession: undefined,
|
||||
payload: { agentType: 'codex', state: 'working', prompt: '' }
|
||||
},
|
||||
'wsl:Ubuntu'
|
||||
)
|
||||
expect(desktop.getStatusSnapshot()[0]).toMatchObject({
|
||||
state: 'working',
|
||||
prompt: 'old task',
|
||||
model: 'old-model',
|
||||
mainAgent: { state: 'working', stateStartedAt: 1000 },
|
||||
subagents: [{ id: 'old-0', state: 'working' }],
|
||||
turnStartedAt: 1_000
|
||||
})
|
||||
} finally {
|
||||
desktop.stop()
|
||||
vi.useRealTimers()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['local', 'relay', 'old-relay', 'old-relay-no-main'] as const)(
|
||||
'separates Codex session identity from live turns on %s',
|
||||
|
||||
+1
-32
@@ -1,7 +1,7 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { AgentHookServer } from '../../../agent-hook-server'
|
||||
import { HOOK_SILENCE_BEFORE_PROGRAM_STATUS_FALLBACK_MS } from '../../../program-status/hook-precedence'
|
||||
import { buildBody, ingestProgramStatusOsc, PANE, postHookEvent } from '../../server.test-fixtures'
|
||||
import { buildBody, ingestProgramStatusOsc, postHookEvent } from '../../server.test-fixtures'
|
||||
|
||||
vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../../../../telemetry/cohort-classifier', () => ({ getCohortAtEmit: () => ({}) }))
|
||||
@@ -12,42 +12,11 @@ afterEach(() => {
|
||||
server?.stop()
|
||||
})
|
||||
|
||||
function oscStatus(state: 'working' | 'done'): void {
|
||||
// OpenCode 2 reports OSC 7501 as `app=opencode`.
|
||||
server!.ingestTerminalStatus({
|
||||
paneKey: PANE,
|
||||
tabId: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
connectionId: null,
|
||||
fromProgramStatus: true,
|
||||
payload: { state, prompt: '', agentType: 'opencode' }
|
||||
})
|
||||
}
|
||||
|
||||
async function hook(hook_event_name: string, prompt = ''): Promise<void> {
|
||||
const body = buildBody({ hook_event_name, sessionID: 'ses_opencode2', prompt })
|
||||
expect((await postHookEvent(server!, body, '/hook/opencode2')).status).toBe(204)
|
||||
}
|
||||
|
||||
it('keeps OpenCode 2 hooks and their session on a pane its OSC 7501 reports as opencode', async () => {
|
||||
server = new AgentHookServer()
|
||||
await server.start({ env: 'production' })
|
||||
oscStatus('working')
|
||||
await hook('SessionBusy', 'rename the branch')
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({
|
||||
agentType: 'opencode2',
|
||||
prompt: 'rename the branch'
|
||||
})
|
||||
|
||||
await hook('SessionIdle')
|
||||
oscStatus('done')
|
||||
expect(server.getStatusSnapshot()[0]).toMatchObject({
|
||||
agentType: 'opencode2',
|
||||
state: 'done',
|
||||
providerSession: { id: 'ses_opencode2' }
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an idle OpenCode 2 pane done while another session in its folder works', async () => {
|
||||
server = new AgentHookServer()
|
||||
await server.start({ env: 'production' })
|
||||
|
||||
@@ -1,33 +1,18 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
allowsArtifactCloudAuthOverride,
|
||||
resolveArtifactCloudApiUrl
|
||||
} from './artifact-cloud-config'
|
||||
import { resolveArtifactCloudApiUrl } from './artifact-cloud-config'
|
||||
|
||||
describe('resolveArtifactCloudApiUrl', () => {
|
||||
it('allows loopback HTTP only in development', () => {
|
||||
expect(
|
||||
resolveArtifactCloudApiUrl(
|
||||
undefined,
|
||||
{ ORCA_ARTIFACTS_API_URL: 'http://127.0.0.1:45961' },
|
||||
false
|
||||
)
|
||||
).toBe('http://127.0.0.1:45961')
|
||||
expect(() => resolveArtifactCloudApiUrl('http://127.0.0.1:45961', {}, true)).toThrow(/HTTPS/)
|
||||
})
|
||||
|
||||
it('rejects origins that could receive an Orca access token', () => {
|
||||
expect(() => resolveArtifactCloudApiUrl('https://example.com', {}, false)).toThrow(
|
||||
/onorca\.dev/
|
||||
)
|
||||
expect(() => resolveArtifactCloudApiUrl('https://share.onorca.dev/path', {}, false)).toThrow(
|
||||
/origin/
|
||||
)
|
||||
})
|
||||
|
||||
it('allows auth token overrides only in non-production development builds', () => {
|
||||
expect(allowsArtifactCloudAuthOverride({}, false)).toBe(true)
|
||||
expect(allowsArtifactCloudAuthOverride({ NODE_ENV: 'production' }, false)).toBe(false)
|
||||
expect(allowsArtifactCloudAuthOverride({}, true)).toBe(false)
|
||||
it('allows both first-party domain families without trusting similar hostnames', () => {
|
||||
for (const origin of ['https://share.onorca.dev', 'https://share.orca.dev']) {
|
||||
expect(resolveArtifactCloudApiUrl(origin, {}, true)).toBe(origin)
|
||||
}
|
||||
for (const origin of [
|
||||
'https://share.orca.dev.example.com',
|
||||
'https://notorca.dev',
|
||||
'https://notonorca.dev',
|
||||
'https://share.onorca.dev.example.com'
|
||||
]) {
|
||||
expect(() => resolveArtifactCloudApiUrl(origin, {}, true)).toThrow()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -18,12 +18,14 @@ export function resolveArtifactCloudApiUrl(
|
||||
const candidate = override?.trim() || env.ORCA_ARTIFACTS_API_URL?.trim()
|
||||
const url = new URL(candidate || PRODUCTION_ARTIFACTS_API_URL)
|
||||
const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname)
|
||||
const firstParty = url.hostname === 'onorca.dev' || url.hostname.endsWith('.onorca.dev')
|
||||
const firstParty = ['onorca.dev', 'orca.dev'].some(
|
||||
(domain) => url.hostname === domain || url.hostname.endsWith(`.${domain}`)
|
||||
)
|
||||
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback && !packaged)) {
|
||||
throw new Error('Artifact API URLs must use HTTPS; local development may use loopback HTTP.')
|
||||
}
|
||||
if (!firstParty && !loopback) {
|
||||
throw new Error('Artifact API URLs must use an onorca.dev or loopback host.')
|
||||
throw new Error('Artifact API URLs must use an onorca.dev, orca.dev, or loopback host.')
|
||||
}
|
||||
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
||||
throw new Error('Artifact API URL must be an origin without credentials, paths, or parameters.')
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import { acquired, fakeClaude, PROVIDER_SESSION_ID } from './claude-structured-session-test-support'
|
||||
import { agentSessionRecordFixture } from '../../../shared/agent-session/lifecycle/agent-session-record.test-fixture'
|
||||
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
it('retains retirement knowledge when the optional title method is missing', async () => {
|
||||
const cli = fakeClaude()
|
||||
const adapter = await acquired(cli)
|
||||
try {
|
||||
const record = agentSessionRecordFixture()
|
||||
record.sessionId = 'session-1'
|
||||
record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID
|
||||
const owner = adapter.captureConversationTitleOwner(record)!
|
||||
expect(owner.isCurrent(record)).toBe(true)
|
||||
expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBeNull()
|
||||
await adapter.closeAll()
|
||||
expect(owner.isCurrent(record)).toBe(false)
|
||||
} finally {
|
||||
await adapter.closeAll()
|
||||
cli.dispose()
|
||||
}
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
@@ -25,13 +25,14 @@ describe('Claude structured dispatch attachment rejections', () => {
|
||||
expect(session.connection.send).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects local images whose aggregate size exceeds twenty MiB', async () => {
|
||||
it('rejects local images whose aggregate size exceeds sixty-four MiB', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'orca-claude-images-'))
|
||||
try {
|
||||
const paths = await Promise.all(
|
||||
Array.from({ length: 5 }, async (_, index) => {
|
||||
Array.from({ length: 2 }, async (_, index) => {
|
||||
const path = join(directory, `${index}.png`)
|
||||
await writeFile(path, Buffer.alloc(5 * 1024 * 1024))
|
||||
await writeFile(path, '')
|
||||
await truncate(path, 32 * 1024 * 1024 + 1)
|
||||
return path
|
||||
})
|
||||
)
|
||||
@@ -43,10 +44,10 @@ describe('Claude structured dispatch attachment rejections', () => {
|
||||
).resolves.toEqual({
|
||||
state: 'rejected',
|
||||
reason:
|
||||
'The images on this message add up to more than 20 MB, so the message was not sent.',
|
||||
'The images on this message add up to more than 64 MB, so the message was not sent.',
|
||||
rejection: {
|
||||
kind: 'attachmentInvalid',
|
||||
attachment: { reason: 'totalTooLarge', limit: 20 * 1024 * 1024 }
|
||||
attachment: { reason: 'totalTooLarge', limit: 64 * 1024 * 1024 }
|
||||
}
|
||||
})
|
||||
expect(session.connection.send).not.toHaveBeenCalled()
|
||||
@@ -59,7 +60,8 @@ describe('Claude structured dispatch attachment rejections', () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'orca-claude-image-'))
|
||||
try {
|
||||
const path = join(directory, 'oversized.png')
|
||||
await writeFile(path, Buffer.alloc(5 * 1024 * 1024 + 1))
|
||||
await writeFile(path, '')
|
||||
await truncate(path, 50 * 1024 * 1024 + 1)
|
||||
const session = sessionFor()
|
||||
const body = userMessage([{ type: 'image-ref', path }])
|
||||
|
||||
@@ -67,10 +69,10 @@ describe('Claude structured dispatch attachment rejections', () => {
|
||||
dispatchClaudeTurn(session, { clientMessageId: 'client-1', body })
|
||||
).resolves.toEqual({
|
||||
state: 'rejected',
|
||||
reason: 'An image on this message is larger than 5 MB, so the message was not sent.',
|
||||
reason: 'An image on this message is larger than 50 MB, so the message was not sent.',
|
||||
rejection: {
|
||||
kind: 'attachmentInvalid',
|
||||
attachment: { reason: 'tooLarge', limit: 5 * 1024 * 1024 }
|
||||
attachment: { reason: 'tooLarge', limit: 50 * 1024 * 1024 }
|
||||
}
|
||||
})
|
||||
expect(session.connection.send).not.toHaveBeenCalled()
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { AgentJournalMessageItem } from '../../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { claudeDispatchMessageContent } from './claude-structured-dispatch-content'
|
||||
@@ -19,4 +22,27 @@ describe('claudeDispatchMessageContent', () => {
|
||||
{ type: 'text', text: '/goal ship the parser' }
|
||||
])
|
||||
})
|
||||
|
||||
it('sends a local image over the API per-image limit for Claude to shrink', async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), 'orca-claude-image-'))
|
||||
try {
|
||||
const path = join(directory, 'retina-screenshot.png')
|
||||
await writeFile(path, Buffer.alloc(6 * 1024 * 1024, 1))
|
||||
|
||||
const content = await claudeDispatchMessageContent(userMessage([{ type: 'image-ref', path }]))
|
||||
|
||||
expect(content).toEqual([
|
||||
{
|
||||
type: 'image',
|
||||
source: {
|
||||
type: 'base64',
|
||||
media_type: 'image/png',
|
||||
data: Buffer.alloc(6 * 1024 * 1024, 1).toString('base64')
|
||||
}
|
||||
}
|
||||
])
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type AgentJournalDispatchRejection
|
||||
} from '../../../shared/agent-session/failures/agent-session-failure-words'
|
||||
import { TUI_AGENT_DISPLAY_NAMES } from '../../../shared/agent-launch/catalog/tui-agent-display-names'
|
||||
import { AGENT_SESSION_ATTACHMENT_MAX_BYTES } from '../../../shared/agent-session/agent-session-attachments'
|
||||
import { claudeRecord } from './journal/claude-structured-item-translation'
|
||||
|
||||
export class ClaudeDispatchContentError extends Error {
|
||||
@@ -51,10 +52,10 @@ export function claudeDispatchContentRejection(error: unknown): AgentJournalDisp
|
||||
return claudeDispatchRejection(agentSessionFailureFact('attachmentUnreadable'))
|
||||
}
|
||||
|
||||
const BYTES_PER_MB = 1024 * 1024
|
||||
const MAX_IMAGE_BYTES = 5 * BYTES_PER_MB
|
||||
// Claude shrinks every image before the API sees it, so these bound host memory, not API limits.
|
||||
const MAX_IMAGE_BYTES = AGENT_SESSION_ATTACHMENT_MAX_BYTES
|
||||
const MAX_IMAGE_COUNT = 20
|
||||
const MAX_TOTAL_IMAGE_BYTES = 20 * BYTES_PER_MB
|
||||
const MAX_TOTAL_IMAGE_BYTES = 64 * 1024 * 1024
|
||||
const MAX_REPLAY_CONTENT_KEY_BYTES = 256
|
||||
|
||||
type ImageBudget = {
|
||||
|
||||
@@ -148,19 +148,4 @@ describe('projectGroups IPC validation', () => {
|
||||
expect(mockStore.addRepo).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses nested imports on an SSH target and never inspects the path locally', async () => {
|
||||
await expect(
|
||||
handlers.get('projectGroups:importNested')!(null, {
|
||||
parentPath: '/srv/platform',
|
||||
groupName: 'Platform',
|
||||
projectPaths: ['/srv/platform/api'],
|
||||
connectionId: 'conn-1',
|
||||
mode: 'group'
|
||||
})
|
||||
).rejects.toThrow('ssh_connection_unavailable')
|
||||
|
||||
expect(mockStore.addRepo).not.toHaveBeenCalled()
|
||||
expect(isGitRepo).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -84,16 +84,6 @@ describe('projectGroups IPC validation', () => {
|
||||
registerRepoHandlers(mockWindow as never, mockStore as never, {} as never)
|
||||
})
|
||||
|
||||
it('refuses SSH nested scans without reading the remote or the local filesystem', async () => {
|
||||
await expect(
|
||||
handlers.get('projectGroups:scanNested')!(null, {
|
||||
path: '/srv/platform',
|
||||
connectionId: 'conn-1'
|
||||
})
|
||||
).rejects.toThrow('ssh_connection_unavailable')
|
||||
expect(isGitRepo).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns partial local scan results after cancellation', async () => {
|
||||
vi.mocked(isGitRepo).mockReturnValue(false)
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-nested-local-cancel-'))
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
listWorktreesMock,
|
||||
removeWorktreeMock,
|
||||
killAllProcessesForWorktreeMock
|
||||
} from './worktrees-test-module-mocks'
|
||||
import { handlers, setupWorktreeHandlers, store } from './worktrees-test-harness'
|
||||
import { SshHostNotServedError } from '../providers/ssh-host-not-served-error'
|
||||
|
||||
vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeScanCacheModule>()),
|
||||
listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks'))
|
||||
.listWorktreesMock,
|
||||
listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).electronModuleMock()
|
||||
)
|
||||
vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks'))
|
||||
.assertWorktreeCleanForRemovalMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock
|
||||
}))
|
||||
vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
describeCreatedWorktree: (await import('./worktrees-test-module-mocks'))
|
||||
.describeCreatedWorktreeMock
|
||||
}))
|
||||
const { getWorktreeRunnerMocks } = vi.hoisted(() => {
|
||||
function createWorktreeRunnerMocks() {
|
||||
return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())()
|
||||
}
|
||||
let runner: ReturnType<typeof createWorktreeRunnerMocks> | undefined
|
||||
return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) }
|
||||
})
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync
|
||||
}))
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync
|
||||
}))
|
||||
vi.mock('../git/remotes/repo-remote-queries', async () => ({
|
||||
getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock
|
||||
}))
|
||||
vi.mock('../git/refs/resolution/repo-branch-conflict', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock,
|
||||
resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveDefaultBaseRefWithLocalGitMock
|
||||
}))
|
||||
vi.mock('../git/repositories/git-username', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
resolveLocalGitUsername: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveLocalGitUsernameMock
|
||||
}))
|
||||
vi.mock('../github/client', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../github/client/lookup/get-pr-for-branch', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../source-control/hosted-review', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hostedReviewModuleMock()
|
||||
)
|
||||
vi.mock('./worktree-symlinks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks'))
|
||||
.findExistingWorktreeSymlinkPathsMock
|
||||
}))
|
||||
vi.mock('../workspace-hooks/hooks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hooksModuleMock()
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('./worktree-logic', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../pty/history/terminal-history-deletion', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock()
|
||||
)
|
||||
vi.mock('../ports/advertised-url-watcher', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock()
|
||||
)
|
||||
vi.mock('../runtime/workspaces/removal/worktree-teardown', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/registry', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/state-cleanup', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock()
|
||||
)
|
||||
|
||||
describe('registerWorktreeHandlers', () => {
|
||||
beforeEach(() => {
|
||||
setupWorktreeHandlers()
|
||||
})
|
||||
|
||||
it('refuses an SSH worktree delete this process does not serve, never deleting here', async () => {
|
||||
const repo = {
|
||||
id: 'repo-ssh',
|
||||
path: '/remote/repo',
|
||||
displayName: 'ssh',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
connectionId: 'conn-1',
|
||||
worktreeBaseRef: null
|
||||
}
|
||||
store.getRepos.mockReturnValue([repo])
|
||||
store.getRepo.mockReturnValue(repo)
|
||||
|
||||
await expect(
|
||||
handlers['worktrees:remove'](null, { worktreeId: 'repo-ssh::/remote/feature-wt' })
|
||||
).rejects.toThrow(SshHostNotServedError)
|
||||
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
expect(removeWorktreeMock).not.toHaveBeenCalled()
|
||||
expect(killAllProcessesForWorktreeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,217 +0,0 @@
|
||||
import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { addWorktreeMock, getBranchConflictKindStrictMock } from './worktrees-test-module-mocks'
|
||||
import { handlers, setupWorktreeHandlers, store } from './worktrees-test-harness'
|
||||
import { SshHostNotServedError } from '../providers/ssh-host-not-served-error'
|
||||
|
||||
vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeScanCacheModule>()),
|
||||
listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks'))
|
||||
.listWorktreesMock,
|
||||
listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).electronModuleMock()
|
||||
)
|
||||
vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks'))
|
||||
.assertWorktreeCleanForRemovalMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock
|
||||
}))
|
||||
vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
describeCreatedWorktree: (await import('./worktrees-test-module-mocks'))
|
||||
.describeCreatedWorktreeMock
|
||||
}))
|
||||
const { getWorktreeRunnerMocks } = vi.hoisted(() => {
|
||||
function createWorktreeRunnerMocks() {
|
||||
return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())()
|
||||
}
|
||||
let runner: ReturnType<typeof createWorktreeRunnerMocks> | undefined
|
||||
return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) }
|
||||
})
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync
|
||||
}))
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync
|
||||
}))
|
||||
vi.mock('../git/remotes/repo-remote-queries', async () => ({
|
||||
getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock
|
||||
}))
|
||||
vi.mock('../git/refs/resolution/repo-branch-conflict', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock,
|
||||
resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveDefaultBaseRefWithLocalGitMock
|
||||
}))
|
||||
vi.mock('../git/repositories/git-username', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
resolveLocalGitUsername: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveLocalGitUsernameMock
|
||||
}))
|
||||
vi.mock('../github/client', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../github/client/lookup/get-pr-for-branch', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../source-control/hosted-review', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hostedReviewModuleMock()
|
||||
)
|
||||
vi.mock('./worktree-symlinks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks'))
|
||||
.findExistingWorktreeSymlinkPathsMock
|
||||
}))
|
||||
vi.mock('../workspace-hooks/hooks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hooksModuleMock()
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('./worktree-logic', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../pty/history/terminal-history-deletion', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock()
|
||||
)
|
||||
vi.mock('../ports/advertised-url-watcher', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock()
|
||||
)
|
||||
vi.mock('../runtime/workspaces/removal/worktree-teardown', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/registry', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/state-cleanup', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock()
|
||||
)
|
||||
|
||||
const REMOTE_REPO_PATH = '/remote/repo'
|
||||
|
||||
function makeRepo(fields: Record<string, unknown>) {
|
||||
return {
|
||||
id: 'repo-1',
|
||||
path: REMOTE_REPO_PATH,
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
worktreeBaseRef: 'origin/main',
|
||||
...fields
|
||||
}
|
||||
}
|
||||
|
||||
function useRepo(repo: ReturnType<typeof makeRepo>): void {
|
||||
store.getRepos.mockReturnValue([repo])
|
||||
store.getRepo.mockReturnValue(repo)
|
||||
store.setWorktreeMeta.mockImplementation((_target: unknown, meta: unknown) => meta)
|
||||
}
|
||||
|
||||
describe('worktrees:create execution host routing', () => {
|
||||
beforeEach(() => {
|
||||
setupWorktreeHandlers()
|
||||
})
|
||||
|
||||
it('refuses a row that names an SSH host only as executionHostId instead of creating locally', async () => {
|
||||
useRepo(makeRepo({ executionHostId: 'ssh:target-a' }))
|
||||
|
||||
await expect(
|
||||
handlers['worktrees:create'](null, { repoId: 'repo-1', name: 'wt' })
|
||||
).rejects.toThrow(SshHostNotServedError)
|
||||
|
||||
expect(addWorktreeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('worktrees:create exact name', () => {
|
||||
beforeEach(() => {
|
||||
setupWorktreeHandlers()
|
||||
})
|
||||
|
||||
// Electron flattens the error to its message, so the renderer reads the code from the trailing token.
|
||||
it('refuses a taken name with the code token instead of suffixing', async () => {
|
||||
getBranchConflictKindStrictMock.mockResolvedValue('local')
|
||||
|
||||
await expect(
|
||||
handlers['worktrees:create'](null, {
|
||||
repoId: 'repo-1',
|
||||
name: 'Login fix',
|
||||
branchIntent: 'create-exact'
|
||||
})
|
||||
).rejects.toThrow(/\nworktree_create_exact_name_taken$/)
|
||||
|
||||
expect(addWorktreeMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -228,45 +228,6 @@ describe('registerWorktreeHandlers', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('prompts for force before removing an Orca-created orphaned worktree directory', async () => {
|
||||
const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-orphan-'))
|
||||
const repoPath = join(parentDir, 'repo')
|
||||
const orphanPath = join(parentDir, 'orphan')
|
||||
const adminWorktreePath = join(repoPath, '.git', 'worktrees', 'orphan')
|
||||
await mkdir(orphanPath, { recursive: true })
|
||||
await mkdir(adminWorktreePath, { recursive: true })
|
||||
await writeFile(join(orphanPath, '.git'), `gitdir: ${adminWorktreePath}\n`)
|
||||
await writeFile(join(adminWorktreePath, 'gitdir'), `${join(orphanPath, '.git')}\n`)
|
||||
const repo = {
|
||||
id: 'repo-1',
|
||||
path: repoPath,
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
worktreeBaseRef: null
|
||||
}
|
||||
store.getRepo.mockReturnValue(repo)
|
||||
store.getRepos.mockReturnValue([repo])
|
||||
mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath)
|
||||
store.getWorktreeMeta.mockReturnValue(
|
||||
makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'runtime' })
|
||||
)
|
||||
|
||||
try {
|
||||
await expect(
|
||||
handlers['worktrees:remove'](null, {
|
||||
worktreeId: `repo-1::${orphanPath}`
|
||||
})
|
||||
).rejects.toThrow('Worktree is no longer registered with Git but its directory remains.')
|
||||
|
||||
await expect(lstat(orphanPath)).resolves.toBeTruthy()
|
||||
expect(removeWorktreeMock).not.toHaveBeenCalled()
|
||||
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await rm(parentDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('refuses an Orca-created unregistered directory with no git marker, even forced, until the user removes it', async () => {
|
||||
const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-leftover-'))
|
||||
const repoPath = join(parentDir, 'repo')
|
||||
@@ -316,69 +277,4 @@ describe('registerWorktreeHandlers', () => {
|
||||
await rm(parentDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects an Orca-created unregistered local directory with a git directory', async () => {
|
||||
const parentDir = await mkdtemp(join(tmpdir(), 'orca-ipc-standalone-'))
|
||||
const repoPath = join(parentDir, 'repo')
|
||||
const standalonePath = join(parentDir, 'standalone')
|
||||
await mkdir(join(standalonePath, '.git'), { recursive: true })
|
||||
store.getRepo.mockReturnValue({
|
||||
id: 'repo-1',
|
||||
path: repoPath,
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
worktreeBaseRef: null
|
||||
})
|
||||
mockKnownFeatureWorktree(join(parentDir, 'real-feature'), repoPath)
|
||||
store.getWorktreeMeta.mockReturnValue(
|
||||
makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'runtime' })
|
||||
)
|
||||
|
||||
try {
|
||||
await expect(
|
||||
handlers['worktrees:remove'](null, {
|
||||
worktreeId: `repo-1::${standalonePath}`,
|
||||
force: true
|
||||
})
|
||||
).rejects.toThrow(`Refusing to delete unregistered worktree path: ${standalonePath}`)
|
||||
|
||||
await expect(lstat(standalonePath)).resolves.toBeTruthy()
|
||||
expect(removeWorktreeMock).not.toHaveBeenCalled()
|
||||
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await rm(parentDir, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('does not inspect or delete a local path for an SSH orphan this process does not serve', async () => {
|
||||
const localPath = await mkdtemp(join(tmpdir(), 'orca-ipc-ssh-missing-fs-'))
|
||||
const repo = {
|
||||
id: 'repo-ssh-missing-fs',
|
||||
path: '/remote/repo',
|
||||
displayName: 'ssh',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
connectionId: 'conn-missing-fs'
|
||||
}
|
||||
store.getRepo.mockReturnValue(repo)
|
||||
store.getWorktreeMeta.mockReturnValue(
|
||||
makeWorktreeMeta({ orcaCreatedAt: Date.now(), orcaCreationSource: 'ssh' })
|
||||
)
|
||||
|
||||
try {
|
||||
await expect(
|
||||
handlers['worktrees:remove'](null, {
|
||||
worktreeId: `${repo.id}::${localPath}`,
|
||||
force: true
|
||||
})
|
||||
).rejects.toThrow('isn’t served by Orca’s server')
|
||||
|
||||
await expect(lstat(localPath)).resolves.toBeTruthy()
|
||||
expect(removeWorktreeMock).not.toHaveBeenCalled()
|
||||
expect(store.removeWorktreeMeta).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await rm(localPath, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,260 +0,0 @@
|
||||
import type * as WorktreeScanCacheModule from '../git/worktrees/catalog/worktree-scan-cache'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { ProviderRequestId } from '../../shared/detected-worktree-provider-contract'
|
||||
import { toSshExecutionHostId } from '../../shared/execution-host'
|
||||
import { getSshProviderAuthority } from '../ssh/connection/authority/ssh-provider-authority'
|
||||
import { listWorktreesMock } from './worktrees-test-module-mocks'
|
||||
import { handlers, ipcEvent, setupWorktreeHandlers, store } from './worktrees-test-harness'
|
||||
|
||||
vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => {
|
||||
return {
|
||||
...(await importOriginal<typeof WorktreeScanCacheModule>()),
|
||||
listWorktrees: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
listWorktreesSharedStrictAllowingTrueEmpty: (await import('./worktrees-test-module-mocks'))
|
||||
.listWorktreesMock,
|
||||
listWorktreesSharedStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('electron', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).electronModuleMock()
|
||||
)
|
||||
vi.mock('../../shared/git/worktrees/git-worktree-porcelain-parser', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
parseWorktreeList: (await import('./worktrees-test-module-mocks')).parseWorktreeListMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal-preflight', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
assertWorktreeCleanForRemoval: (await import('./worktrees-test-module-mocks'))
|
||||
.assertWorktreeCleanForRemovalMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addWorktree: (await import('./worktrees-test-module-mocks')).addWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/creation/worktree-sparse-add', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
addSparseWorktree: (await import('./worktrees-test-module-mocks')).addSparseWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
removeWorktree: (await import('./worktrees-test-module-mocks')).removeWorktreeMock
|
||||
}))
|
||||
|
||||
vi.mock('../git/worktrees/removal/worktree-branch-removal', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
forceDeleteLocalBranch: (await import('./worktrees-test-module-mocks')).forceDeleteLocalBranchMock
|
||||
}))
|
||||
vi.mock('../git/worktrees/catalog/worktree-listing', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
listWorktreesStrict: (await import('./worktrees-test-module-mocks')).listWorktreesMock,
|
||||
describeCreatedWorktree: (await import('./worktrees-test-module-mocks'))
|
||||
.describeCreatedWorktreeMock
|
||||
}))
|
||||
const { getWorktreeRunnerMocks } = vi.hoisted(() => {
|
||||
function createWorktreeRunnerMocks() {
|
||||
return (async () => (await import('./worktrees-test-module-mocks')).gitRunnerModuleMock())()
|
||||
}
|
||||
let runner: ReturnType<typeof createWorktreeRunnerMocks> | undefined
|
||||
return { getWorktreeRunnerMocks: () => (runner ??= createWorktreeRunnerMocks()) }
|
||||
})
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileAsync: (await getWorktreeRunnerMocks()).gitExecFileAsync
|
||||
}))
|
||||
|
||||
vi.mock('../git/command-runner/git-exec-file-sync', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
gitExecFileSync: (await getWorktreeRunnerMocks()).gitExecFileSync
|
||||
}))
|
||||
vi.mock('../git/remotes/repo-remote-queries', async () => ({
|
||||
getDefaultRemote: (await import('./worktrees-test-module-mocks')).getDefaultRemoteMock
|
||||
}))
|
||||
vi.mock('../git/refs/resolution/repo-branch-conflict', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).gitBranchConflictModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/refs/resolution/repo-default-base-ref', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
getDefaultBaseRefAsync: (await import('./worktrees-test-module-mocks')).getBaseRefDefaultMock,
|
||||
resolveDefaultBaseRefWithLocalGit: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveDefaultBaseRefWithLocalGitMock
|
||||
}))
|
||||
vi.mock('../git/repositories/git-username', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
resolveLocalGitUsername: (await import('./worktrees-test-module-mocks'))
|
||||
.resolveLocalGitUsernameMock
|
||||
}))
|
||||
vi.mock('../github/client', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../github/client/lookup/get-pr-for-branch', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).githubClientModuleMock()
|
||||
)
|
||||
vi.mock('../source-control/hosted-review', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hostedReviewModuleMock()
|
||||
)
|
||||
vi.mock('./worktree-symlinks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeSymlinksModuleMock()
|
||||
)
|
||||
|
||||
vi.mock('../git/worktrees/content-paths/worktree-symlink-detection', async (importOriginal) => ({
|
||||
...(await importOriginal<Record<string, unknown>>()),
|
||||
findExistingWorktreeSymlinkPaths: (await import('./worktrees-test-module-mocks'))
|
||||
.findExistingWorktreeSymlinkPathsMock
|
||||
}))
|
||||
vi.mock('../workspace-hooks/hooks', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).hooksModuleMock()
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-runner-script-text', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupRunnerScriptTextModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/worktree-runner-script', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeRunnerScriptModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/effective-hook-config', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).effectiveHookConfigModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../workspace-hooks/setup-hook-env-vars', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).setupHookEnvVarsModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('./worktree-logic', async (importOriginal) =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeLogicModuleMock(
|
||||
(await importOriginal()) as Record<string, unknown>
|
||||
)
|
||||
)
|
||||
vi.mock('../pty/history/terminal-history-deletion', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).terminalHistoryDeletionModuleMock()
|
||||
)
|
||||
vi.mock('../ports/advertised-url-watcher', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).advertisedUrlWatcherModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-scan-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupScanSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/space-analysis/workspace-space-analysis-snapshot', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceSpaceAnalysisSnapshotModuleMock()
|
||||
)
|
||||
vi.mock('../workspaces/cleanup/workspace-cleanup-removal-snapshot-prune', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).workspaceCleanupRemovalSnapshotPruneModuleMock()
|
||||
)
|
||||
vi.mock('../runtime/workspaces/removal/worktree-teardown', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).worktreeTeardownModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/registry', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyRegistryModuleMock()
|
||||
)
|
||||
vi.mock('./pty/provider/state-cleanup', async () =>
|
||||
(await import('./worktrees-test-module-mocks')).ptyStateCleanupModuleMock()
|
||||
)
|
||||
|
||||
describe('registerWorktreeHandlers', () => {
|
||||
beforeEach(() => {
|
||||
setupWorktreeHandlers()
|
||||
})
|
||||
|
||||
// Runtime rows bypass local stale GC too, so only authoritative host scans retire them (#17776).
|
||||
|
||||
// Runtime ownership plus a connectionId is contradictory; findExactRepoOwner must refuse it.
|
||||
|
||||
it('fails closed for duplicate exact owners and ambiguous legacy repo IDs', async () => {
|
||||
const sshRepo = {
|
||||
id: 'shared-repo',
|
||||
path: '/remote/repo-a',
|
||||
displayName: 'remote repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
connectionId: 'target-a'
|
||||
}
|
||||
const duplicateSshRepo = { ...sshRepo, path: '/remote/repo-b' }
|
||||
const localRepo = { ...sshRepo, path: '/local/repo', connectionId: undefined }
|
||||
store.getRepos.mockReturnValue([sshRepo, duplicateSshRepo, localRepo])
|
||||
const expectedAuthority = getSshProviderAuthority('target-a')
|
||||
|
||||
const qualified = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: 'request-1' as ProviderRequestId,
|
||||
repoId: 'shared-repo',
|
||||
executionHostId: toSshExecutionHostId('target-a'),
|
||||
expectedAuthority
|
||||
})
|
||||
const legacy = await handlers['worktrees:listDetected'](null, { repoId: 'shared-repo' })
|
||||
|
||||
expect(qualified).toMatchObject({
|
||||
status: 'ambiguous-owner',
|
||||
providerRequestId: 'request-1',
|
||||
executionHostId: 'ssh:target-a'
|
||||
})
|
||||
expect(legacy).toEqual({
|
||||
repoId: 'shared-repo',
|
||||
authoritative: false,
|
||||
source: 'metadata-fallback',
|
||||
worktrees: []
|
||||
})
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects runtime hosts, wrong SSH targets, and missing authority', async () => {
|
||||
const requestId = 'request-1' as ProviderRequestId
|
||||
const expectedAuthority = getSshProviderAuthority('target-a')
|
||||
|
||||
const runtimeResult = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: requestId,
|
||||
repoId: 'repo-1',
|
||||
executionHostId: 'runtime:runtime-a'
|
||||
})
|
||||
const wrongTargetResult = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: requestId,
|
||||
repoId: 'repo-1',
|
||||
executionHostId: toSshExecutionHostId('target-b'),
|
||||
expectedAuthority
|
||||
})
|
||||
const missingAuthorityResult = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: requestId,
|
||||
repoId: 'repo-1',
|
||||
executionHostId: toSshExecutionHostId('target-a')
|
||||
})
|
||||
const zeroOwnerResult = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: requestId,
|
||||
repoId: 'repo-1',
|
||||
executionHostId: toSshExecutionHostId('target-a'),
|
||||
expectedAuthority
|
||||
})
|
||||
store.getRepos.mockReturnValue([
|
||||
{
|
||||
id: 'repo-1',
|
||||
path: '/remote/repo',
|
||||
displayName: 'repo',
|
||||
badgeColor: '#000',
|
||||
addedAt: 0,
|
||||
connectionId: 'target-b',
|
||||
executionHostId: toSshExecutionHostId('target-a')
|
||||
}
|
||||
])
|
||||
const wrongProviderOwnerResult = await handlers['worktrees:listDetected'](ipcEvent, {
|
||||
providerRequestId: requestId,
|
||||
repoId: 'repo-1',
|
||||
executionHostId: toSshExecutionHostId('target-a'),
|
||||
expectedAuthority
|
||||
})
|
||||
|
||||
expect(runtimeResult).toMatchObject({ status: 'rejected' })
|
||||
expect(wrongTargetResult).toMatchObject({ status: 'rejected' })
|
||||
expect(missingAuthorityResult).toMatchObject({ status: 'rejected' })
|
||||
expect(zeroOwnerResult).toMatchObject({ status: 'ambiguous-owner' })
|
||||
expect(wrongProviderOwnerResult).toMatchObject({ status: 'rejected' })
|
||||
expect(listWorktreesMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -50,13 +50,6 @@ export class JournalNewestTurn {
|
||||
return this.root?.latest.item ?? null
|
||||
}
|
||||
|
||||
/** The newest turn or clear, when it is a turn still running. */
|
||||
running(): { item: AgentJournalRenderItem; turnId: string } | null {
|
||||
const item = this.read()
|
||||
const turn = item ? readAgentJournalTurn(item.body) : null
|
||||
return item && turn?.state === 'running' ? { item, turnId: turn.turnId } : null
|
||||
}
|
||||
|
||||
/** Releasing Resume marks must be written after this position. */
|
||||
failure(): number {
|
||||
const winner = this.root?.winner
|
||||
|
||||
@@ -15,6 +15,7 @@ import type {
|
||||
import { agentJournalItemKey } from '../../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentSessionContextUsage } from '../../../shared/agent-session/agent-session-context-usage'
|
||||
import { latestStructuredAgentContextFacts } from '../../../shared/agent-session/structured-agent-session-context-usage'
|
||||
import { runningStructuredAgentSessionTurnItemBySequence } from '../../../shared/agent-session/view/structured-agent-session-live-turn'
|
||||
import { readAgentJournalTurn } from '../../../shared/agent-session/lifecycle/agent-session-turn-record'
|
||||
import { journalWroteBeforeOpen } from './replay/journal-cursor'
|
||||
import type { JournalHostDatabase } from './database/journal-host-database'
|
||||
@@ -229,8 +230,9 @@ export class AgentSessionJournal {
|
||||
hasRecordedItem = (itemId: string): boolean =>
|
||||
this.state.items.has(itemId) || this.state.tombstones.has(itemId)
|
||||
|
||||
/** Read from the per-row turn index so hot readers never rescan history; host projection decides current work. */
|
||||
runningTurn = () => journalInputOrder(this.state).newestTurn.running()
|
||||
/** Read the journal's running turn without allocating a snapshot; host projection decides current work. */
|
||||
runningTurn = (): { item: journal.AgentJournalRenderItem; turnId: string } | null =>
|
||||
runningStructuredAgentSessionTurnItemBySequence(this.state.items.values())
|
||||
|
||||
newestTurn = (): journal.AgentJournalTurnLifecycle | null =>
|
||||
readAgentJournalTurn(journalInputOrder(this.state).newestTurn.read()?.body)
|
||||
|
||||
@@ -62,8 +62,7 @@ export class StructuredAgentSessionHost {
|
||||
private readonly lifetime: HostTypes.StructuredAgentSessionConversationLifetime
|
||||
private readonly conversationDelivery: conversation.StructuredAgentSessionConversationDelivery
|
||||
private readonly eventRecovery: StructuredAgentSessionEventRecovery
|
||||
/** History and work-state reads, which open a chat at rest without starting its agent. */
|
||||
readonly backgroundTasks: BackgroundTasks
|
||||
private readonly backgroundTasks: BackgroundTasks
|
||||
readonly restartResume: StructuredAgentSessionRestartResume
|
||||
|
||||
readonly usageLimitContinue: ReturnType<typeof usageLimit.start>
|
||||
|
||||
+1
-5
@@ -6,14 +6,12 @@ import { AtRestCommandCatalog } from '../at-rest-command-catalog'
|
||||
function catalogWithSkills() {
|
||||
let stamp = 'a'
|
||||
let skills = ['old-skill']
|
||||
let scans = 0
|
||||
const catalog = new AtRestCommandCatalog({
|
||||
label: 'test',
|
||||
accepts: () => true,
|
||||
resolveWorkspacePath: async () => tmpdir(),
|
||||
stamp: async () => stamp,
|
||||
scan: async () => {
|
||||
scans += 1
|
||||
return {
|
||||
commands: skills.map((name) => ({ name, kind: 'skill' as const, path: `/s/${name}` })),
|
||||
fromAgent: true
|
||||
@@ -22,7 +20,6 @@ function catalogWithSkills() {
|
||||
})
|
||||
return {
|
||||
catalog,
|
||||
scans: () => scans,
|
||||
install: (name: string, nextStamp: string) => {
|
||||
skills = [...skills, name]
|
||||
stamp = nextStamp
|
||||
@@ -34,13 +31,12 @@ const names = (commands: { name: string }[] | undefined) => commands?.map(({ nam
|
||||
|
||||
describe('at-rest commands before the TTL', () => {
|
||||
it('rescans on a menu open once the skill sources changed', async () => {
|
||||
const { catalog, scans, install } = catalogWithSkills()
|
||||
const { catalog, install } = catalogWithSkills()
|
||||
const record = hostTestRestingOptionsRecord()
|
||||
expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill'])
|
||||
|
||||
install('perf-scan', 'b')
|
||||
expect(names(await catalog.settled(record, 1_000, true))).toEqual(['old-skill', 'perf-scan'])
|
||||
expect(scans()).toBe(2)
|
||||
catalog.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
-28
@@ -6,9 +6,6 @@ import type {
|
||||
AgentSessionHistoryRequest,
|
||||
AgentSessionHistoryResult
|
||||
} from '../../../../../shared/agent-session/agent-session-wire'
|
||||
import type { AgentSessionWorkState } from '../../../../../shared/agent-session/agent-session-work-state'
|
||||
import { AgentSessionRefusalError } from '../../../../../shared/agent-session/failures/agent-session-wire-refusals'
|
||||
import { AGENT_SESSION_NOT_ATTACHED } from '../../operations/structured-agent-session-mutation-refusals'
|
||||
import type { AgentSessionBackgroundTaskState } from '../../../../../shared/agent-session/agent-session-background-task-wire'
|
||||
import type { AgentChildWorkView } from '../../../../../shared/agent-status/child-work/agent-status-child-work-view'
|
||||
import { structuredChildWorkLegacyTasks } from '../../../../../shared/agent-session/structured-agent-session-child-work-legacy'
|
||||
@@ -88,31 +85,6 @@ export class StructuredAgentSessionBackgroundTaskChannel {
|
||||
}
|
||||
}
|
||||
|
||||
/** What a waiter decides from, from the sources history pages state, without building a page. */
|
||||
async workState(sessionId: string): Promise<AgentSessionWorkState> {
|
||||
await this.conversation(sessionId)
|
||||
const work = hostStructuredAgentSessionCurrentWork(
|
||||
{ store: this.deps.store, sessions: this.sessions },
|
||||
sessionId
|
||||
)
|
||||
if (!work) {
|
||||
throw new AgentSessionRefusalError(AGENT_SESSION_NOT_ATTACHED)
|
||||
}
|
||||
const queue = this.subscribers.readQueuePublication(sessionId)
|
||||
const fence = this.deps.store.getConversation(sessionId)?.currentFence
|
||||
return {
|
||||
working: work.working(),
|
||||
actionablePrompt: work.hasActionablePrompt(),
|
||||
...(queue !== undefined
|
||||
? {
|
||||
queuedMessageIds: (queue.queuedMessages ?? []).map((card) => card.messageId),
|
||||
nextQueuedMessageId: queue.nextQueuedMessageId
|
||||
}
|
||||
: {}),
|
||||
...(fence !== undefined ? { fence } : {})
|
||||
}
|
||||
}
|
||||
|
||||
async currentRequests(request: AgentSessionCurrentRequestsRead) {
|
||||
await this.conversation(request.sessionId)
|
||||
const work = hostStructuredAgentSessionCurrentWork(
|
||||
|
||||
@@ -70,28 +70,6 @@ function rig(
|
||||
}
|
||||
}
|
||||
|
||||
it('tries CLI reuse once while independent generation retries, and skips it on manual regeneration', async () => {
|
||||
const reuse = vi.fn()
|
||||
const generate = vi.fn<StructuredChatNamingDeps['generate']>(
|
||||
async (_record, _prompt, _current, automatic) => {
|
||||
if (automatic) {
|
||||
reuse()
|
||||
}
|
||||
return generate.mock.calls.length === 1
|
||||
? { error: 'Retry independent generation' }
|
||||
: { name: 'Login repair' }
|
||||
}
|
||||
)
|
||||
const state = rig(generate)
|
||||
state.start()
|
||||
await state.done()
|
||||
expect(state.record().conversationName).toBe('Login repair')
|
||||
expect(reuse).toHaveBeenCalledOnce()
|
||||
state.handler.regenerate('chat-1')
|
||||
await state.done()
|
||||
expect(reuse).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it.each(['owner', 'same-text rename'] as const)(
|
||||
'rejects a queued title write after %s changes',
|
||||
async (change) => {
|
||||
|
||||
@@ -21,15 +21,6 @@ describe('planOpenCodeRootModelRewrite', () => {
|
||||
).toBe(`& opencode --standalone${tail}`)
|
||||
})
|
||||
|
||||
it('uses the last of repeated models and an existing --standalone', () => {
|
||||
expect(
|
||||
planOpenCodeRootModelRewrite(
|
||||
`opencode2 --standalone ${q(['--model', 'a/b', '--model=c/d'], 'posix')}`,
|
||||
'posix'
|
||||
)
|
||||
).toMatchObject({ command: 'opencode2 --standalone', model: 'c/d' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['posix', `opencode ${q(['run', '--model', 'a/b'], 'posix')}`],
|
||||
['posix', `opencode ${q(['./pkg', '--model', 'a/b'], 'posix')}`],
|
||||
@@ -51,13 +42,4 @@ describe('planOpenCodeRootModelRewrite', () => {
|
||||
] as const)('leaves %s `%s` as typed', (shell, command) => {
|
||||
expect(planOpenCodeRootModelRewrite(command, shell, 'C:\\')).toBeNull()
|
||||
})
|
||||
|
||||
it('probes the primary agent only for a new session on it', () => {
|
||||
expect(
|
||||
planOpenCodeRootModelRewrite(
|
||||
`opencode ${q(['-s', 'ses_1', '--model', 'a/b'], 'posix')}`,
|
||||
'posix'
|
||||
)?.probeExecutable
|
||||
).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,124 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { RpcResponse } from '../rpc/core'
|
||||
import { AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY } from '../../../shared/agent-session/agent-session-runtime-capabilities'
|
||||
import { RuntimeClient, RuntimeClientError } from '../../../cli/runtime-client'
|
||||
import { CHAT_HANDLERS } from '../../../cli/handlers/chat'
|
||||
import {
|
||||
openStructuredCodexRpcHarness,
|
||||
SESSION,
|
||||
THREAD,
|
||||
TURN,
|
||||
type StructuredCodexRpcHarness
|
||||
} from '../rpc/methods/structured-sessions/structured-codex-session-rpc-test-harness'
|
||||
|
||||
const NEWEST_MARKER = 'newest-row-marker'
|
||||
|
||||
let harness: StructuredCodexRpcHarness | undefined
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
await harness?.dispose()
|
||||
harness = undefined
|
||||
})
|
||||
|
||||
/** The CLI's own client, answered by the host's dispatcher in the local CLI's caller context. */
|
||||
function cliClient(open: StructuredCodexRpcHarness) {
|
||||
const client = new RuntimeClient('/tmp/orca-chat-wait-test', 60_000, null, null)
|
||||
vi.spyOn(client, 'getCliStatus').mockResolvedValue({
|
||||
id: 'status',
|
||||
ok: true,
|
||||
result: {
|
||||
app: { running: true, pid: 1 },
|
||||
runtime: {
|
||||
state: 'ready',
|
||||
reachable: true,
|
||||
runtimeId: 'runtime-1',
|
||||
capabilities: [AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY]
|
||||
},
|
||||
graph: { state: 'ready' }
|
||||
},
|
||||
_meta: { runtimeId: 'runtime-1' }
|
||||
})
|
||||
vi.spyOn(client, 'call').mockImplementation(async (method: string, params?: unknown) => {
|
||||
const response: RpcResponse = await open.call(method, params)
|
||||
if (!response.ok) {
|
||||
throw new RuntimeClientError(response.error.code, response.error.message)
|
||||
}
|
||||
return response
|
||||
})
|
||||
return client
|
||||
}
|
||||
|
||||
function agentMessage(id: string, text: string): void {
|
||||
harness!.codex.notify('item/completed', {
|
||||
threadId: THREAD,
|
||||
turnId: TURN,
|
||||
item: { type: 'agentMessage', id, text }
|
||||
})
|
||||
}
|
||||
|
||||
/** A running turn holding `rows` earlier replies and one newest reply of `newestBytes`. */
|
||||
async function seedRunningTurn(rows: number, newestBytes: number): Promise<void> {
|
||||
harness!.codex.notify('turn/started', { threadId: THREAD, turn: { id: TURN } })
|
||||
for (let index = 0; index < rows; index += 1) {
|
||||
agentMessage(`older-${index}`, `Older reply ${index}.`)
|
||||
}
|
||||
agentMessage('newest', `${NEWEST_MARKER} ${'x'.repeat(newestBytes)}`)
|
||||
await vi.waitFor(async () => {
|
||||
const page = await harness!.call('agentSession.history', {
|
||||
sessionId: SESSION,
|
||||
direction: 'tail',
|
||||
limit: 1
|
||||
})
|
||||
expect(JSON.stringify(page)).toContain(NEWEST_MARKER)
|
||||
})
|
||||
}
|
||||
|
||||
/** Lets the command's next checks run until it prints, then surfaces its result or failure. */
|
||||
async function settle(command: Promise<void>, logs: string[]): Promise<void> {
|
||||
for (let second = 0; second < 10 && logs.length === 0; second += 1) {
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
}
|
||||
await command
|
||||
}
|
||||
|
||||
describe('chat send --wait over the real host', () => {
|
||||
it('returns the completed turn when the host lacks agentSession.workState', async () => {
|
||||
harness = await openStructuredCodexRpcHarness(
|
||||
[],
|
||||
{},
|
||||
{ localCli: true, omitMethods: ['agentSession.workState'] }
|
||||
)
|
||||
await harness.ok('agentSession.create', harness.createIntentParams())
|
||||
const client = cliClient(harness)
|
||||
const logs: string[] = []
|
||||
vi.spyOn(console, 'log').mockImplementation((line: string) => logs.push(line))
|
||||
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
|
||||
const sending = CHAT_HANDLERS['chat send']!({
|
||||
flags: new Map<string, string | boolean>([
|
||||
['session', SESSION],
|
||||
['text', 'Run the tests'],
|
||||
['wait', true]
|
||||
]),
|
||||
client,
|
||||
cwd: '/tmp',
|
||||
json: true
|
||||
})
|
||||
await vi.waitFor(() =>
|
||||
expect(harness!.codex.live().calls.map((c) => c.method)).toContain('turn/start')
|
||||
)
|
||||
await seedRunningTurn(1, 16)
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
harness.codex.notify('turn/completed', {
|
||||
threadId: THREAD,
|
||||
turn: { id: TURN, status: 'completed' }
|
||||
})
|
||||
await settle(sending, logs)
|
||||
expect(JSON.parse(logs.join('\n')).result).toMatchObject({
|
||||
delivery: 'submitted',
|
||||
settled: 'done',
|
||||
entries: [{ text: 'Older reply 0.' }, { text: `${NEWEST_MARKER} ${'x'.repeat(16)}` }]
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -435,4 +435,89 @@ describe('OrcaRuntimeService', () => {
|
||||
expect(getSession().terminalLayoutsByTabId['durable-tab']).toBeUndefined()
|
||||
expect(flushOrThrow).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
// Main-owned layouts restore a ready headless graph when the window closes.
|
||||
it.skipIf(ORCA_LAYOUT_OWNER_IS_MAIN)(
|
||||
'closes a paired session tab after the desktop window is gone',
|
||||
async () => {
|
||||
const { runtimeStore, getSession } = makeRuntimeStoreWithWorkspaceSession(
|
||||
makeWorkspaceSessionWithHeadlessTerminal()
|
||||
)
|
||||
const closeTerminalTab = vi.fn(async () => undefined)
|
||||
const kill = vi.fn(() => true)
|
||||
const runtime = new OrcaRuntimeService(
|
||||
withDurableRuntimeStore({ ...runtimeStore, flushOrThrow: vi.fn() })
|
||||
)
|
||||
runtime.setNotifier({ closeTerminal: vi.fn(), closeTerminalTab } as never)
|
||||
runtime.setPtyController({
|
||||
write: () => true,
|
||||
kill,
|
||||
getForegroundProcess: async () => null,
|
||||
listProcesses: async () => []
|
||||
})
|
||||
runtime.syncWindowGraph(1, {
|
||||
tabs: [
|
||||
{
|
||||
tabId: 'host-tab',
|
||||
worktreeId: TEST_WORKTREE_ID,
|
||||
title: 'Durable',
|
||||
activeLeafId: HEADLESS_LEAF_ID,
|
||||
layout: null
|
||||
}
|
||||
],
|
||||
leaves: [
|
||||
{
|
||||
tabId: 'host-tab',
|
||||
worktreeId: TEST_WORKTREE_ID,
|
||||
leafId: HEADLESS_LEAF_ID,
|
||||
paneRuntimeId: 1,
|
||||
ptyId: 'persisted-pty'
|
||||
}
|
||||
],
|
||||
mobileSessionTabs: [
|
||||
{
|
||||
worktree: TEST_WORKTREE_ID,
|
||||
publicationEpoch: 'renderer:paired-close',
|
||||
snapshotVersion: 1,
|
||||
activeGroupId: 'group-1',
|
||||
activeTabId: `host-tab::${HEADLESS_LEAF_ID}`,
|
||||
activeTabType: 'terminal',
|
||||
tabs: [
|
||||
{
|
||||
type: 'terminal',
|
||||
id: `host-tab::${HEADLESS_LEAF_ID}`,
|
||||
parentTabId: 'host-tab',
|
||||
leafId: HEADLESS_LEAF_ID,
|
||||
ptyId: 'persisted-pty',
|
||||
title: 'Durable',
|
||||
isActive: true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
})
|
||||
runtime.registerPty('persisted-pty', TEST_WORKTREE_ID, null, {
|
||||
tabId: 'host-tab',
|
||||
leafId: HEADLESS_LEAF_ID
|
||||
})
|
||||
|
||||
const closePaired = () =>
|
||||
runtime.closeMobileSessionTab(`id:${TEST_WORKTREE_ID}`, 'host-tab', {
|
||||
reason: 'user',
|
||||
clientNavigationId: 'device-a'
|
||||
})
|
||||
runtime.markGraphUnavailable(1)
|
||||
runtime.setNotifier(null)
|
||||
runtime.attachWindow(2)
|
||||
|
||||
await expect(closePaired()).rejects.toThrow('runtime_unavailable')
|
||||
|
||||
runtime.markGraphUnavailable(2)
|
||||
|
||||
await expect(closePaired()).resolves.toEqual({ closed: true, retirementConfirmed: true })
|
||||
expect(closeTerminalTab).not.toHaveBeenCalled()
|
||||
expect(getSession().tabsByWorktree[TEST_WORKTREE_ID] ?? []).toEqual([])
|
||||
expect(getSession().terminalLayoutsByTabId['host-tab']).toBeUndefined()
|
||||
}
|
||||
)
|
||||
})
|
||||
|
||||
@@ -84,7 +84,6 @@ it('keeps showing an open approval behind more closed ones than the row bound',
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
const ids = row.approvals?.map(({ approval }) => approval.approvalId)
|
||||
expect(ids).toHaveLength(100)
|
||||
expect(ids?.[0]).toBe('apr_still_open')
|
||||
expect(ids?.at(-1)).toBe('apr_149')
|
||||
})
|
||||
@@ -124,31 +123,3 @@ it('closes an open approval once its Dispatch stops running, at the time it ende
|
||||
])
|
||||
expect(row.approvals?.[0].approval.expiresAt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('reads a close no one named, after its Dispatch ended, as the worker ending', () => {
|
||||
const { db, deps, run, assign } = fixture()
|
||||
const dispatch = assign('term_worker')
|
||||
db.insertMessage({
|
||||
id: approvalReportId(dispatch.id, 'apr_unnamed', 'closed'),
|
||||
from: 'term_worker',
|
||||
to: `run:${run.id}`,
|
||||
subject: 'apr_unnamed',
|
||||
type: 'status',
|
||||
runId: run.id,
|
||||
payload: JSON.stringify({
|
||||
approval: {
|
||||
v: 1,
|
||||
approvalId: 'apr_unnamed',
|
||||
state: 'answered',
|
||||
worker: { handle: 'term_worker', dispatchId: dispatch.id, taskId: dispatch.task_id },
|
||||
summary: { title: 'Allow Bash?', detail: null, reason: null },
|
||||
allowedActions: [],
|
||||
outcome: { by: 'unknown', decision: null, reason: null, reasonDelivered: false }
|
||||
}
|
||||
})
|
||||
})
|
||||
db.completeDispatch(dispatch.id)
|
||||
|
||||
const [row] = buildCrewSnapshot('term_coord', deps).sections.managing
|
||||
expect(row.approvals?.map(({ approval }) => approval.outcome?.by)).toEqual(['worker-ended'])
|
||||
})
|
||||
|
||||
+2
-62
@@ -43,16 +43,6 @@ const USER_NO: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: "The user doesn't want to proceed with this tool use. The tool use was rejected."
|
||||
}
|
||||
const AUTO_BLOCK: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: 'Permission for this command was denied by a built-in Claude Code safety check, not by the user.'
|
||||
}
|
||||
// An allowed command that then fails (probe 2026-11-11, the owner's live case).
|
||||
const FAILED: ClaudeToolResult = {
|
||||
isError: true,
|
||||
text: "Exit code 1\n(eval):14: parse error near `\\n'"
|
||||
}
|
||||
const RAN: ClaudeToolResult = { isError: false, text: '59' }
|
||||
/** What the transcript holds: the hook decision Claude took, then the tool's result. */
|
||||
const record = (
|
||||
result: ClaudeToolResult | null,
|
||||
@@ -147,14 +137,11 @@ function hook(
|
||||
}
|
||||
}
|
||||
|
||||
function postToolUse(
|
||||
toolUseId: string,
|
||||
hookEventName: 'PostToolUse' | 'PostToolUseFailure' = 'PostToolUse'
|
||||
): AgentHookEventPayload {
|
||||
function postToolUse(toolUseId: string): AgentHookEventPayload {
|
||||
return {
|
||||
paneKey: PANE,
|
||||
connectionId: null,
|
||||
hookEventName,
|
||||
hookEventName: 'PostToolUse',
|
||||
toolUseId,
|
||||
payload: { state: 'working', prompt: '', agentType: 'claude' }
|
||||
}
|
||||
@@ -232,23 +219,6 @@ describe('terminal worker approval holds', () => {
|
||||
expect(ctx.closedWith()[0]).toMatchObject({ state: 'answered', by: 'unknown' })
|
||||
})
|
||||
|
||||
it.each([
|
||||
['allowed, and the command succeeds', record(RAN, 'allow')],
|
||||
['allowed, and the command fails', record(FAILED, 'allow')],
|
||||
['allowed, and the command is still running', record(null, 'allow')],
|
||||
['allowed by a Claude that records no hook decision, and the command fails', record(FAILED)]
|
||||
])("takes Orca's allow when %s", async (_, written) => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1', () => {
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.screen.record = written
|
||||
})
|
||||
const approvalId = await opened(ctx, asked)
|
||||
|
||||
expect(await answer(ctx, approvalId, 'allow')).toMatchObject({ ok: true })
|
||||
expect(asked.replies).toEqual([{ behavior: 'allow' }])
|
||||
})
|
||||
|
||||
it("doesn't take Orca's allow when the person's No won the race", async () => {
|
||||
const ctx = setup()
|
||||
const approvalId = await opened(
|
||||
@@ -271,36 +241,6 @@ describe('terminal worker approval holds', () => {
|
||||
])
|
||||
})
|
||||
|
||||
it("names a Yes in the terminal whose command failed as allowed in the worker's terminal", async () => {
|
||||
const ctx = setup()
|
||||
await opened(ctx, hook('tool-1'))
|
||||
ctx.screen.lines = AFTER
|
||||
ctx.holds.observe(postToolUse('tool-1', 'PostToolUseFailure'))
|
||||
|
||||
expect(ctx.closedWith()).toEqual([
|
||||
{
|
||||
state: 'answered',
|
||||
by: 'worker-terminal',
|
||||
decision: 'allow',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
}
|
||||
])
|
||||
})
|
||||
|
||||
it("names Claude's 2:00 auto-block as an expiry", async () => {
|
||||
const ctx = setup()
|
||||
await closedInTerminal(ctx, AUTO_BLOCK)
|
||||
|
||||
expect(ctx.closedWith()[1]).toEqual({
|
||||
state: 'expired',
|
||||
by: 'auto',
|
||||
decision: 'deny',
|
||||
reason: null,
|
||||
reasonDelivered: false
|
||||
})
|
||||
})
|
||||
|
||||
it("tells the coordinator to send the user to the terminal when the hook is gone but the dialog isn't", async () => {
|
||||
const ctx = setup()
|
||||
const asked = hook('tool-1')
|
||||
|
||||
@@ -45,7 +45,6 @@ import {
|
||||
CreateParams,
|
||||
CreateSupportParams,
|
||||
HistoryParams,
|
||||
WorkStateParams,
|
||||
RewindParams,
|
||||
SendParams,
|
||||
SleepWorkspaceParams,
|
||||
@@ -192,16 +191,6 @@ export const STRUCTURED_AGENT_SESSION_METHODS = [
|
||||
)
|
||||
}
|
||||
}),
|
||||
// Waiters poll this instead of history: no history page or running-turn scan, and no transcript in the reply.
|
||||
defineMethod({
|
||||
name: 'agentSession.workState',
|
||||
permission: 'workspace',
|
||||
params: WorkStateParams,
|
||||
handler: async (params, ctx) =>
|
||||
(await requireInstalledHost(ctx, params.sessionId)).backgroundTasks.workState(
|
||||
params.sessionId
|
||||
)
|
||||
}),
|
||||
STRUCTURED_AGENT_SESSION_SUBSCRIBE_METHOD,
|
||||
defineMethod({
|
||||
name: 'agentSession.unsubscribe',
|
||||
|
||||
+3
-7
@@ -181,13 +181,11 @@ export type StructuredCodexRpcHarness = {
|
||||
export async function openStructuredCodexRpcHarness(
|
||||
clientCapabilities: readonly RuntimeCapability[] = DEFAULT_CLIENT_CAPABILITIES,
|
||||
/** What the transport stamps, as a paired device's authenticated socket does. */
|
||||
transport: { clientId?: string; pairedDeviceId?: string } = {},
|
||||
/** The local CLI names no client kind; an older host lacks newer methods. */
|
||||
options: { localCli?: boolean; omitMethods?: readonly string[] } = {}
|
||||
transport: { clientId?: string; pairedDeviceId?: string } = {}
|
||||
): Promise<StructuredCodexRpcHarness> {
|
||||
const client = {
|
||||
clientId: 'device-a',
|
||||
...(options.localCli ? {} : { clientKind: 'runtime' as const }),
|
||||
clientKind: 'runtime' as const,
|
||||
clientCapabilities,
|
||||
...transport
|
||||
}
|
||||
@@ -249,9 +247,7 @@ export async function openStructuredCodexRpcHarness(
|
||||
}
|
||||
const dispatcher = new RpcDispatcher({
|
||||
runtime: runtime as unknown as OrcaRuntimeService,
|
||||
methods: STRUCTURED_AGENT_SESSION_METHODS.filter(
|
||||
(method) => !options.omitMethods?.includes(method.name)
|
||||
)
|
||||
methods: STRUCTURED_AGENT_SESSION_METHODS
|
||||
})
|
||||
const call: StructuredCodexRpcHarness['call'] = async (method, params) => {
|
||||
const replies: RpcResponse[] = []
|
||||
|
||||
@@ -123,6 +123,20 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend
|
||||
}
|
||||
}
|
||||
|
||||
/** Null when no window is attached: there is no renderer to fence. A booting or reloading one throws. */
|
||||
protected captureRendererGraphFence(): number | null {
|
||||
return this.authoritativeWindowId === null ? null : this.captureReadyGraphEpoch()
|
||||
}
|
||||
|
||||
protected assertRendererGraphFence(fence: number | null): void {
|
||||
if (fence !== null) {
|
||||
this.assertStableReadyGraph(fence)
|
||||
} else if (this.authoritativeWindowId !== null) {
|
||||
// A window attached mid-operation; its renderer owns the graph again.
|
||||
throw new Error('runtime_unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
protected resolveFolderWorkspaceConnectionId(workspace: FolderWorkspace): string | null {
|
||||
const repos = this.store?.getRepos() ?? []
|
||||
const projectGroups = this.store?.getProjectGroups?.() ?? []
|
||||
|
||||
@@ -47,14 +47,14 @@ export abstract class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWi
|
||||
tabId: string,
|
||||
options: MobileSessionTabCloseOptions = {}
|
||||
): Promise<MobileSessionTabCloseOutcome> {
|
||||
const graphEpoch = options.clientNavigationId ? this.captureReadyGraphEpoch() : null
|
||||
const graphFence = options.clientNavigationId ? this.captureRendererGraphFence() : undefined
|
||||
const explicitWorktreeId = this.getExplicitSessionWorktreeIdSelector(worktreeSelector)
|
||||
const worktreeId =
|
||||
explicitWorktreeId ?? (await this.resolveWorkspaceSelector(worktreeSelector)).id
|
||||
this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId)
|
||||
const observedPtyIds = await this.refreshMobileSessionPtyRecords()
|
||||
if (graphEpoch !== null) {
|
||||
this.assertStableReadyGraph(graphEpoch)
|
||||
if (graphFence !== undefined) {
|
||||
this.assertRendererGraphFence(graphFence)
|
||||
}
|
||||
this.restoreLivePairedRendererSessionOwnedMobileTerminals(worktreeId)
|
||||
const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId)
|
||||
|
||||
+8
@@ -26,6 +26,14 @@ export abstract class OrcaRuntimeWithHasLiveOrPersistedServeOrSshOwnedPtyBinding
|
||||
...args: Parameters<SessionGraphAuthority['assertStableReadyGraph']>
|
||||
): ReturnType<SessionGraphAuthority['assertStableReadyGraph']>
|
||||
|
||||
protected abstract captureRendererGraphFence(
|
||||
...args: Parameters<SessionGraphAuthority['captureRendererGraphFence']>
|
||||
): ReturnType<SessionGraphAuthority['captureRendererGraphFence']>
|
||||
|
||||
protected abstract assertRendererGraphFence(
|
||||
...args: Parameters<SessionGraphAuthority['assertRendererGraphFence']>
|
||||
): ReturnType<SessionGraphAuthority['assertRendererGraphFence']>
|
||||
|
||||
protected abstract resolvePtyTabCloseSurfaceAuthority(
|
||||
...args: Parameters<MobileTerminalSurface['resolvePtyTabCloseSurfaceAuthority']>
|
||||
): ReturnType<MobileTerminalSurface['resolvePtyTabCloseSurfaceAuthority']>
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { OrcaRuntimeService } from '../../orca-runtime'
|
||||
import { OrchestrationDb } from '../../orchestration/db/orchestration-db'
|
||||
import { isOrcaSessionId } from '../../../../shared/orca-session-address'
|
||||
|
||||
const CHAT = 'claude_11111111_1111_4111_8111_111111111111'
|
||||
|
||||
it("reads a chat's approvals on its own Run's changes, never on terminal identity notices", async () => {
|
||||
if (!isOrcaSessionId(CHAT)) {
|
||||
throw new Error('fixture id')
|
||||
}
|
||||
const runtime = new OrcaRuntimeService()
|
||||
const db = new OrchestrationDb(':memory:')
|
||||
runtime.setOrchestrationDb(db)
|
||||
const runs = vi.spyOn(db, 'runsBoundToCoordinator')
|
||||
const stop = runtime.subscribeOrchestrationWorkerApprovals(`orca_session_id:${CHAT}`, () => {})
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve))
|
||||
const reads = runs.mock.calls.length
|
||||
|
||||
// What every agent status or tab title change sends: terminal identity's default topology notice.
|
||||
for (let i = 0; i < 50; i++) {
|
||||
runtime.crewChanges.notify()
|
||||
await settle()
|
||||
}
|
||||
expect(runs.mock.calls.length - reads).toBe(0)
|
||||
|
||||
db.createRun({
|
||||
objective: 'Coordinate',
|
||||
coordinatorHandle: null,
|
||||
coordinatorPaneKey: null,
|
||||
coordinatorOrcaSessionId: CHAT
|
||||
})
|
||||
await settle()
|
||||
expect(runs.mock.calls.length - reads).toBe(1)
|
||||
stop()
|
||||
})
|
||||
@@ -6,14 +6,16 @@ export type SttRecognizerInit = {
|
||||
sampleRate: number
|
||||
/** Absent = auto-detect. */
|
||||
language?: string
|
||||
/** Silero VAD GGUF; when present, offline models commit text at each pause. */
|
||||
/** Silero VAD GGUF; when present, offline models show live text at each pause. */
|
||||
vadModelPath?: string
|
||||
}
|
||||
|
||||
export type SttRecognizerEvent =
|
||||
/** One decoded offline chunk; `samples` counts the stream's input-rate samples decoded so far. */
|
||||
/** One committed offline chunk; `samples` counts the stream's input-rate samples committed so far. */
|
||||
| { type: 'chunk'; streamId: string; text: string; samples: number }
|
||||
/** Pause-cut streams only: speech was heard that no chunk has committed yet. */
|
||||
/** The uncommitted phrases' live text so far; the next chunk replaces it. */
|
||||
| { type: 'partial'; streamId: string; text: string }
|
||||
/** Pause-cut streams only: speech was heard whose text hasn't arrived yet. */
|
||||
| { type: 'speech-pending'; streamId: string; pending: boolean }
|
||||
/** A load step finished, so a slow load is told apart from a hung GPU. */
|
||||
| { type: 'loading' }
|
||||
|
||||
@@ -24,7 +24,7 @@ export type SttEvent =
|
||||
| { type: 'ready' }
|
||||
| { type: 'partial'; text?: string }
|
||||
| { type: 'final'; text?: string }
|
||||
/** Speech was heard that no final has committed yet; only from pause-cut on-device models. */
|
||||
/** Speech was heard whose text hasn't arrived yet; only from pause-cut on-device models. */
|
||||
| { type: 'speech-pending'; pending: boolean }
|
||||
| { type: 'stopped' }
|
||||
| { type: 'error'; error?: string }
|
||||
|
||||
@@ -2,8 +2,9 @@ import { availableParallelism } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import type * as TranscribeCpp from 'transcribe-cpp'
|
||||
import { appendDictationText } from '../../shared/dictation-transcript-spacing'
|
||||
import { resampleToRate } from './stt-audio-resample'
|
||||
import { OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
import { OFFLINE_DECODE_CHUNK_SECONDS, OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
import { VadPauseSegmenter } from './stt-vad-pause-segmenter'
|
||||
import type { SttRecognizer, SttRecognizerInit, SttRecognizerPost } from './stt-recognizer'
|
||||
|
||||
@@ -44,8 +45,12 @@ type StreamCoverage = {
|
||||
inputSamples: number
|
||||
resampledSamples: number
|
||||
reportedSamples: number
|
||||
/** Stream position the last phrase decode reached, for its speed check. */
|
||||
decodedSamples: number
|
||||
slowPhraseDecodes: number
|
||||
speechPending: boolean
|
||||
/** Phrases since the last commit and their live text. */
|
||||
span: { audio: Float32Array[]; samples: number; texts: string[] }
|
||||
}
|
||||
|
||||
// Whisper pads every decode to a 30 s window, so each phrase costs a full decode. Where that takes longer than the
|
||||
@@ -56,6 +61,9 @@ const SLOW_PHRASE_DECODES_BEFORE_NO_CUTS = 2
|
||||
// Dropped silence still counts as covered; report it so the host's replay buffer and stall watch don't grow through long pauses.
|
||||
const SILENCE_COVERAGE_REPORT_SECONDS = 5
|
||||
|
||||
// The CPU fallback keeps uncommitted audio for a replay and takes over 30 s of it for a stalled GPU.
|
||||
const COMMIT_AFTER_SECONDS = 20
|
||||
|
||||
// Optional: without it dictation still works, with text only at the decode bound and at stop.
|
||||
async function loadSileroVad(
|
||||
transcribe: typeof TranscribeCpp,
|
||||
@@ -128,8 +136,10 @@ export async function createTranscribeCppRecognizer(
|
||||
inputSamples: 0,
|
||||
resampledSamples: 0,
|
||||
reportedSamples: 0,
|
||||
decodedSamples: 0,
|
||||
slowPhraseDecodes: 0,
|
||||
speechPending: false
|
||||
speechPending: false,
|
||||
span: { audio: [], samples: 0, texts: [] }
|
||||
}
|
||||
if (vad && vadModel) {
|
||||
stream.segmenter = new VadPauseSegmenter(
|
||||
@@ -162,9 +172,13 @@ export async function createTranscribeCppRecognizer(
|
||||
// The first run compiles GPU pipelines (seconds on Metal); pay it while loading, not on the first stop.
|
||||
await transcribeChunk(new Float32Array(Math.round(modelRate / 2)), baseOptions)
|
||||
|
||||
// Stream position (model-rate samples) the segmenter has handed on, less chunks still waiting to be decoded.
|
||||
const position = (stream: StreamCoverage, undecoded: number) =>
|
||||
stream.resampledSamples - stream.segmenter.heldSamples - undecoded
|
||||
|
||||
// Coverage is in input-rate samples so the host can trim the audio it keeps for a CPU replay.
|
||||
const report = (streamId: string, stream: StreamCoverage, text: string, undecoded: number) => {
|
||||
const covered = stream.resampledSamples - stream.segmenter.heldSamples - undecoded
|
||||
const covered = position(stream, undecoded)
|
||||
stream.reportedSamples = covered
|
||||
post({
|
||||
type: 'chunk',
|
||||
@@ -177,28 +191,59 @@ export async function createTranscribeCppRecognizer(
|
||||
// Canceled streams, until their queued discard runs; also covers a finish that already closed its stream.
|
||||
const canceled = new Set<string>()
|
||||
|
||||
const decode = async (streamId: string, stream: StreamCoverage, chunks: Float32Array[]) => {
|
||||
const spanLimit = OFFLINE_DECODE_CHUNK_SECONDS * modelRate
|
||||
|
||||
// The span's phrases decode again together, so a pause mid-sentence doesn't capitalize the words after it.
|
||||
const commit = async (streamId: string, stream: StreamCoverage, undecoded: number) => {
|
||||
const { audio, texts } = stream.span
|
||||
if (audio.length === 0 || canceled.has(streamId)) {
|
||||
return
|
||||
}
|
||||
stream.span = { audio: [], samples: 0, texts: [] }
|
||||
const text =
|
||||
audio.length === 1 && texts.length === 1
|
||||
? texts[0]
|
||||
: (await transcribeChunk(joinAudio(audio), stream.options)).trim()
|
||||
report(streamId, stream, text, undecoded)
|
||||
}
|
||||
|
||||
/** `live`: decode each phrase as it ends for live text; at stop only the commit decodes. */
|
||||
const decode = async (
|
||||
streamId: string,
|
||||
stream: StreamCoverage,
|
||||
chunks: Float32Array[],
|
||||
live: boolean
|
||||
) => {
|
||||
let undecoded = chunks.reduce((total, chunk) => total + chunk.length, 0)
|
||||
for (const chunk of chunks) {
|
||||
if (canceled.has(streamId)) {
|
||||
return
|
||||
}
|
||||
const startedAt = performance.now()
|
||||
const text = await transcribeChunk(chunk, stream.options)
|
||||
const decodeMs = performance.now() - startedAt
|
||||
const spokenSince = stream.reportedSamples
|
||||
undecoded -= chunk.length
|
||||
report(streamId, stream, text.trim(), undecoded)
|
||||
if (stream.vad) {
|
||||
noteDecodeSpeed(
|
||||
stream,
|
||||
decodeMs,
|
||||
((stream.reportedSamples - spokenSince) / modelRate) * 1000
|
||||
)
|
||||
if (stream.span.samples + chunk.length > spanLimit) {
|
||||
await commit(streamId, stream, undecoded)
|
||||
}
|
||||
undecoded -= chunk.length
|
||||
stream.span.audio.push(chunk)
|
||||
stream.span.samples += chunk.length
|
||||
if (!live) {
|
||||
continue
|
||||
}
|
||||
const startedAt = performance.now()
|
||||
const text = (await transcribeChunk(chunk, stream.options)).trim()
|
||||
const decodeMs = performance.now() - startedAt
|
||||
stream.span.texts.push(text)
|
||||
post({ type: 'partial', streamId, text: stream.span.texts.reduce(appendDictationText, '') })
|
||||
const reached = position(stream, undecoded)
|
||||
if (stream.vad) {
|
||||
noteDecodeSpeed(stream, decodeMs, ((reached - stream.decodedSamples) / modelRate) * 1000)
|
||||
}
|
||||
stream.decodedSamples = reached
|
||||
}
|
||||
const dropped = stream.resampledSamples - stream.segmenter.heldSamples - stream.reportedSamples
|
||||
if (dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) {
|
||||
if (stream.resampledSamples - stream.reportedSamples >= COMMIT_AFTER_SECONDS * modelRate) {
|
||||
await commit(streamId, stream, 0)
|
||||
}
|
||||
const dropped = position(stream, 0) - stream.reportedSamples
|
||||
if (stream.span.samples === 0 && dropped >= SILENCE_COVERAGE_REPORT_SECONDS * modelRate) {
|
||||
report(streamId, stream, '', 0)
|
||||
}
|
||||
}
|
||||
@@ -244,7 +289,7 @@ export async function createTranscribeCppRecognizer(
|
||||
const phrases = await stream.segmenter.push(resampled)
|
||||
// A cut phrase stays pending until its text is posted.
|
||||
notePendingSpeech(streamId, stream, phrases.length > 0 || !!stream.segmenter.phraseOpen)
|
||||
await decode(streamId, stream, phrases)
|
||||
await decode(streamId, stream, phrases, true)
|
||||
notePendingSpeech(streamId, stream, !!stream.segmenter.phraseOpen)
|
||||
},
|
||||
async finish(streamId) {
|
||||
@@ -253,7 +298,8 @@ export async function createTranscribeCppRecognizer(
|
||||
return
|
||||
}
|
||||
try {
|
||||
await decode(streamId, stream, await stream.segmenter.flush())
|
||||
await decode(streamId, stream, await stream.segmenter.flush(), false)
|
||||
await commit(streamId, stream, 0)
|
||||
notePendingSpeech(streamId, stream, false)
|
||||
} finally {
|
||||
stream.vad?.dispose()
|
||||
@@ -268,3 +314,16 @@ export async function createTranscribeCppRecognizer(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function joinAudio(parts: Float32Array[]): Float32Array {
|
||||
if (parts.length === 1) {
|
||||
return parts[0]
|
||||
}
|
||||
const joined = new Float32Array(parts.reduce((total, part) => total + part.length, 0))
|
||||
let offset = 0
|
||||
for (const part of parts) {
|
||||
joined.set(part, offset)
|
||||
offset += part.length
|
||||
}
|
||||
return joined
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { OfflineAudioChunker } from './stt-offline-audio-chunker'
|
||||
// Silero's own defaults: a frame at or above this is speech; inside speech, one below the second is silence.
|
||||
const SPEECH_PROBABILITY = 0.5
|
||||
const SILENCE_PROBABILITY = 0.35
|
||||
// A pause this long commits the phrase before it. Shorter cuts split phrases, and each piece gets its own capital and full stop.
|
||||
// A pause this long ends the phrase before it, which then decodes for live text; every cut costs a decode.
|
||||
export const VAD_PAUSE_SECONDS = 0.6
|
||||
// Silence kept ahead of detected speech so a soft first syllable isn't clipped.
|
||||
const SPEECH_PREROLL_SECONDS = 0.4
|
||||
|
||||
@@ -9,12 +9,16 @@ import type { GitStatusEntry } from '../../../../shared/git/status/git-status-ty
|
||||
import { ConflictBanner, ConflictPlaceholderView, ConflictReviewPanel } from './ConflictComponents'
|
||||
import { ImageViewer, MonacoEditor } from './editor-lazy-views'
|
||||
import { EditorFileLoadErrorView } from './EditorFileLoadErrorView'
|
||||
import type { FileContent } from './editor-panel-content-types'
|
||||
import {
|
||||
HOST_STARTED,
|
||||
USER_RETRY,
|
||||
type FileContent,
|
||||
type ReloadContentOptions
|
||||
} from './editor-panel-content-types'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import type { EditorConflictNavigation } from './useEditorConflictNavigation'
|
||||
|
||||
// Retry is a user act: it may start a stopped WSL distro.
|
||||
const USER_RETRY = { wakeWslDistro: true }
|
||||
|
||||
export function EditorConflictReviewSurface({
|
||||
activeFile,
|
||||
@@ -43,7 +47,7 @@ export function EditorConflictReviewSurface({
|
||||
) => EditorConflictNavigation | undefined
|
||||
handleContentChangeForFile: (file: OpenFile, content: string) => void
|
||||
handleSaveForFile: (file: OpenFile, content: string) => Promise<boolean>
|
||||
reloadContent: (file: OpenFile, options?: { wakeWslDistro?: boolean }) => void
|
||||
reloadContent: (file: OpenFile, options?: ReloadContentOptions) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const openConflictReviewFile = useAppStore((s) => s.openConflictReviewFile)
|
||||
@@ -163,7 +167,7 @@ export function EditorConflictReviewSurface({
|
||||
worktreeId={contentFile.worktreeId}
|
||||
// Borrowed views reload through their owning workspace.
|
||||
onRetry={() => reloadContent(recordView ?? contentFile, USER_RETRY)}
|
||||
onHostStarted={() => reloadContent(recordView ?? contentFile)}
|
||||
onHostStarted={() => reloadContent(recordView ?? contentFile, HOST_STARTED)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -12,7 +12,12 @@ import { EditorDiffFileSurface } from './EditorDiffFileSurface'
|
||||
import { EditorEditFileSurface } from './EditorEditFileSurface'
|
||||
import { EditorFileLoadErrorView } from './EditorFileLoadErrorView'
|
||||
import { MarkdownPreviewSizeGate } from './markdown-preview/render-tree/MarkdownPreviewSizeGate'
|
||||
import type { FileContent } from './editor-panel-content-types'
|
||||
import {
|
||||
HOST_STARTED,
|
||||
USER_RETRY,
|
||||
type FileContent,
|
||||
type ReloadContentOptions
|
||||
} from './editor-panel-content-types'
|
||||
import { buildPdfScalePreferenceKey } from './pdf-scale-preference-storage'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useEditorConflictNavigation } from './useEditorConflictNavigation'
|
||||
@@ -20,7 +25,6 @@ import { useMarkdownDocuments } from './markdown/documents/useMarkdownDocuments'
|
||||
import type { MarkdownRenderState } from './markdown/render-mode/markdown-render-mode'
|
||||
|
||||
// Retry is a user act: it may start a stopped WSL distro.
|
||||
const USER_RETRY = { wakeWslDistro: true }
|
||||
|
||||
const noopCloseMarkdownTableOfContents = (): void => {}
|
||||
|
||||
@@ -101,7 +105,7 @@ export function EditorContent({
|
||||
handleDirtyStateHint: (dirty: boolean) => void
|
||||
handleSave: (content: string) => Promise<boolean>
|
||||
handleSaveForFile: (file: OpenFile, content: string) => Promise<boolean>
|
||||
reloadContent: (file: OpenFile, options?: { wakeWslDistro?: boolean }) => void
|
||||
reloadContent: (file: OpenFile, options?: ReloadContentOptions) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const editorViewStateKey =
|
||||
@@ -212,7 +216,7 @@ export function EditorContent({
|
||||
code={fileContent.loadErrorCode}
|
||||
worktreeId={activeFile.worktreeId}
|
||||
onRetry={() => reloadContent(activeFile, USER_RETRY)}
|
||||
onHostStarted={() => reloadContent(activeFile)}
|
||||
onHostStarted={() => reloadContent(activeFile, HOST_STARTED)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
import type { EditorConflictNavigation } from './useEditorConflictNavigation'
|
||||
import { EditorFileLoadErrorView } from './EditorFileLoadErrorView'
|
||||
import { RecoverableRenderErrorBoundary } from '../error-boundaries/RecoverableRenderErrorBoundary'
|
||||
import type { FileContent } from './editor-panel-content-types'
|
||||
import {
|
||||
HOST_STARTED,
|
||||
USER_RETRY,
|
||||
type FileContent,
|
||||
type ReloadContentOptions
|
||||
} from './editor-panel-content-types'
|
||||
import { CustomEditorExternalChangeBanner } from './external-changes/CustomEditorExternalChangeBanner'
|
||||
import { PluginFileTypeSuggestion } from './PluginFileTypeSuggestion'
|
||||
import { BinaryFileDefaultAppButton } from './BinaryFileDefaultAppButton'
|
||||
@@ -31,7 +36,6 @@ import PluginCustomEditorFrame from './PluginCustomEditorFrame'
|
||||
import PluginBytesCustomEditorSurface from './PluginBytesCustomEditorSurface'
|
||||
|
||||
// Retry is a user act: it may start a stopped WSL distro.
|
||||
const USER_RETRY = { wakeWslDistro: true }
|
||||
|
||||
const noopEditorContentChange = (_content: string): void => {}
|
||||
const noopEditorSave = async (_content: string): Promise<boolean> => false
|
||||
@@ -109,7 +113,7 @@ export function EditorEditFileSurface({
|
||||
handleContentChange: (content: string) => void
|
||||
handleDirtyStateHint: (dirty: boolean) => void
|
||||
handleSave: (content: string) => Promise<boolean>
|
||||
reloadContent: (file: OpenFile, options?: { wakeWslDistro?: boolean }) => void
|
||||
reloadContent: (file: OpenFile, options?: ReloadContentOptions) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
if (activeFile.conflict?.kind === 'conflict-placeholder') {
|
||||
@@ -140,7 +144,7 @@ export function EditorEditFileSurface({
|
||||
code={fileContent.loadErrorCode}
|
||||
worktreeId={activeFile.worktreeId}
|
||||
onRetry={() => reloadContent(activeFile, USER_RETRY)}
|
||||
onHostStarted={() => reloadContent(activeFile)}
|
||||
onHostStarted={() => reloadContent(activeFile, HOST_STARTED)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { formatFileLoadErrorMessage } from './file-load-error-copy'
|
||||
import { displayIpcErrorMessage } from '@/runtime/errors/ipc-error'
|
||||
import { isFileTooLargeCodeMessage } from '../../../../shared/file-write/file-write-disk-precondition'
|
||||
import { WORKTREE_HOST_UNRESOLVED_CODE } from './editor-panel-content-types'
|
||||
import { useStoppedWslHost } from '../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { useWslHostReadOutage } from '../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { WslHostStoppedNotice } from '../wsl-host-stopped/WslHostStoppedNotice'
|
||||
|
||||
// Localize by machine code; stored English remains readable for logs without coupling upstream state checks to UI language.
|
||||
@@ -39,20 +39,21 @@ export function EditorFileLoadErrorView({
|
||||
}: {
|
||||
message: string
|
||||
code?: string
|
||||
/** The file's workspace; a stopped WSL host there gets Start instead of this error. */
|
||||
/** The file's workspace; a stopped or still-connecting WSL host there gets its notice instead of this error. */
|
||||
worktreeId?: string
|
||||
onRetry: () => void
|
||||
/** Reloads after Start without asking to wake again: the click already booted the host. */
|
||||
onHostStarted?: () => void
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const stoppedWslHost = useStoppedWslHost(worktreeId)
|
||||
if (stoppedWslHost) {
|
||||
const wslHostOutage = useWslHostReadOutage(worktreeId)
|
||||
if (wslHostOutage) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center bg-editor-surface p-6 text-sm">
|
||||
<WslHostStoppedNotice
|
||||
environmentId={stoppedWslHost.environmentId}
|
||||
distro={stoppedWslHost.distro}
|
||||
environmentId={wslHostOutage.environmentId}
|
||||
distro={wslHostOutage.distro}
|
||||
connecting={wslHostOutage.connecting}
|
||||
size="sm"
|
||||
onStarted={onHostStarted}
|
||||
/>
|
||||
|
||||
@@ -23,6 +23,17 @@ export const WORKTREE_HOST_UNRESOLVED_CODE = 'editor_host_workspace_unresolved'
|
||||
export const WORKTREE_HOST_UNRESOLVED_ERROR =
|
||||
"The host couldn't find this file's workspace. It may have been removed, or the host may not know about it yet. Retry, or close this tab from the tab strip."
|
||||
|
||||
export type ReloadContentOptions = {
|
||||
wakeWslDistro?: boolean
|
||||
/** Skip a file that is no longer failed, such as one already reloaded when its host answered. */
|
||||
onlyIfFailed?: boolean
|
||||
}
|
||||
|
||||
/** A user's Retry may boot a stopped WSL distro. */
|
||||
export const USER_RETRY: ReloadContentOptions = { wakeWslDistro: true }
|
||||
/** After Start: the host is already up, and the editor's retry may have reloaded the file. */
|
||||
export const HOST_STARTED: ReloadContentOptions = { onlyIfFailed: true }
|
||||
|
||||
export type FileContent = {
|
||||
mediaUrl?: string
|
||||
size?: number
|
||||
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { Editor } from '@tiptap/core'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { createRichMarkdownHtmlSuperscriptLinkContext } from '../citations/rich-markdown-html-superscript-link-context'
|
||||
import { createRichMarkdownEditorCodec } from '../document/rich-markdown-source-transport'
|
||||
import { encodeRawMarkdownHtmlForRichEditor } from '../raw-source/raw-markdown-html'
|
||||
import { createRichMarkdownExtensions } from '../schema/rich-markdown-extensions'
|
||||
import { handleRichMarkdownEditorClick } from './rich-markdown-editor-click-routing'
|
||||
|
||||
const editors: Editor[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const editor of editors.splice(0)) {
|
||||
editor.destroy()
|
||||
}
|
||||
})
|
||||
|
||||
function createDocLinkEditor(): Editor {
|
||||
const codec = createRichMarkdownEditorCodec()
|
||||
const editor = new Editor({
|
||||
element: document.body.appendChild(document.createElement('div')),
|
||||
extensions: createRichMarkdownExtensions({ codec }),
|
||||
content: encodeRawMarkdownHtmlForRichEditor('See [[docs/guide|some label]] next', codec),
|
||||
contentType: 'markdown'
|
||||
})
|
||||
editors.push(editor)
|
||||
return editor
|
||||
}
|
||||
|
||||
function docLinkEnd(editor: Editor): number {
|
||||
let end = -1
|
||||
editor.state.doc.descendants((node, pos) => {
|
||||
if (node.type.name === 'markdownDocLink') {
|
||||
end = pos + node.nodeSize
|
||||
}
|
||||
})
|
||||
return end
|
||||
}
|
||||
|
||||
// posAtCoords puts a click on the right half of an inline atom at the position after it.
|
||||
function modClickAt(editor: Editor, pos: number, target: Element): string[] {
|
||||
const opened: string[] = []
|
||||
const event = new MouseEvent('click', { metaKey: true })
|
||||
Object.defineProperty(event, 'target', { value: target })
|
||||
handleRichMarkdownEditorClick({
|
||||
activateMarkdownLink: () => undefined,
|
||||
editorRef: { current: editor },
|
||||
event,
|
||||
filePath: '/repo/docs/index.md',
|
||||
isMac: true,
|
||||
htmlSuperscriptLinkContext: createRichMarkdownHtmlSuperscriptLinkContext({
|
||||
sourceFilePath: '/repo/docs/index.md',
|
||||
worktreeId: 'worktree-1',
|
||||
worktreeRoot: '/repo',
|
||||
sourceOwner: { kind: 'local' }
|
||||
}),
|
||||
markdownCommentsRef: { current: [] },
|
||||
markdownSourceLineOffsetRef: { current: 0 },
|
||||
onOpenDocLinkRef: { current: (docTarget) => opened.push(docTarget) },
|
||||
pos,
|
||||
rootRef: { current: null },
|
||||
scrollRichMarkdownReviewNoteCardIntoView: () => undefined,
|
||||
view: editor.view,
|
||||
worktreeId: 'worktree-1',
|
||||
worktreeRoot: '/repo'
|
||||
})
|
||||
return opened
|
||||
}
|
||||
|
||||
describe('rich markdown modifier-click on a wikilink', () => {
|
||||
it('opens the wikilink from the right half of its label', () => {
|
||||
const editor = createDocLinkEditor()
|
||||
const label = editor.view.dom.querySelector('[data-doc-link-target]')
|
||||
expect(label).not.toBeNull()
|
||||
|
||||
expect(modClickAt(editor, docLinkEnd(editor), label!)).toEqual(['docs/guide'])
|
||||
})
|
||||
})
|
||||
+15
-1
@@ -28,6 +28,7 @@ import type { RichMarkdownHtmlSuperscriptLinkContext } from '../citations/rich-m
|
||||
import type { MutableRefObject } from 'react'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import type { EditorView } from '@tiptap/pm/view'
|
||||
import type { Node as ProseMirrorNode } from '@tiptap/pm/model'
|
||||
import type { HttpLinkSourceOwner } from '@/lib/browser/navigation/http-link-routing'
|
||||
import type { DiffComment } from '../../../../../../shared/diff-comment-types'
|
||||
|
||||
@@ -98,7 +99,7 @@ export function handleRichMarkdownEditorClick({
|
||||
}
|
||||
return false
|
||||
}
|
||||
const clickedNode = view.state.doc.nodeAt(pos)
|
||||
const clickedNode = getClickedNode(view, pos, event)
|
||||
if (clickedNode?.type.name === 'image') {
|
||||
return activateMarkdownImageClick({
|
||||
activateMarkdownLink,
|
||||
@@ -183,6 +184,19 @@ function activateMarkdownImageClick({
|
||||
return true
|
||||
}
|
||||
|
||||
// posAtCoords resolves a click on an inline atom's right half to the position after it.
|
||||
function getClickedNode(view: EditorView, pos: number, event: MouseEvent): ProseMirrorNode | null {
|
||||
const before = view.state.doc.resolve(pos).nodeBefore
|
||||
if (
|
||||
before?.isAtom &&
|
||||
event.target instanceof Node &&
|
||||
view.nodeDOM(pos - before.nodeSize)?.contains(event.target)
|
||||
) {
|
||||
return before
|
||||
}
|
||||
return view.state.doc.nodeAt(pos)
|
||||
}
|
||||
|
||||
function getClickedLinkHref(view: EditorView, event: MouseEvent): string {
|
||||
const target =
|
||||
event.target instanceof Element
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react'
|
||||
import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
import type { useAppStore } from '@/store'
|
||||
import type { DiffContent, FileContent } from './editor-panel-content-types'
|
||||
import type { DiffContent, FileContent, ReloadContentOptions } from './editor-panel-content-types'
|
||||
import {
|
||||
useEditorPanelExternalContentEvents,
|
||||
usePruneClosedEditorContent
|
||||
@@ -28,7 +28,7 @@ type UseEditorPanelContentStateParams = {
|
||||
type UseEditorPanelContentStateResult = {
|
||||
fileContents: Record<string, FileContent>
|
||||
diffContents: Record<string, DiffContent>
|
||||
reloadContent: (file: OpenFile, options?: { wakeWslDistro?: boolean }) => void
|
||||
reloadContent: (file: OpenFile, options?: ReloadContentOptions) => void
|
||||
}
|
||||
|
||||
export function useEditorPanelContentState({
|
||||
@@ -42,6 +42,7 @@ export function useEditorPanelContentState({
|
||||
const [fileContents, setFileContents] = useState<Record<string, FileContent>>({})
|
||||
const [diffContents, setDiffContents] = useState<Record<string, DiffContent>>({})
|
||||
const diffContentsRef = useRef(diffContents)
|
||||
const fileContentsRef = useRef(fileContents)
|
||||
const fileLoadRetryAttemptsRef = useRef<Record<string, number>>({})
|
||||
// Generation fences keep slow superseded reads from overwriting newer content.
|
||||
const fileReadGenerationRef = useRef<Record<string, number>>({})
|
||||
@@ -63,11 +64,12 @@ export function useEditorPanelContentState({
|
||||
useLayoutEffect(() => {
|
||||
// Why: event-driven readers must only observe state from committed renders.
|
||||
diffContentsRef.current = diffContents
|
||||
fileContentsRef.current = fileContents
|
||||
openFilesRef.current = openFiles
|
||||
editorViewModeRef.current = editorViewMode
|
||||
isVisibleRef.current = isVisible
|
||||
activeContentFileIdRef.current = activeContentFileId
|
||||
}, [activeContentFileId, diffContents, editorViewMode, isVisible, openFiles])
|
||||
}, [activeContentFileId, diffContents, editorViewMode, fileContents, isVisible, openFiles])
|
||||
|
||||
const invalidateFileContent = useCallback((fileIds: string[]): void => {
|
||||
const uniqueIds = new Set(fileIds)
|
||||
@@ -136,7 +138,7 @@ export function useEditorPanelContentState({
|
||||
|
||||
// Route explicit reloads by mode so diff banners refresh diff bodies instead of plain-file caches.
|
||||
const reloadContent = useCallback(
|
||||
(file: OpenFile, options?: { wakeWslDistro?: boolean }): void => {
|
||||
(file: OpenFile, options?: ReloadContentOptions): void => {
|
||||
if (file.mode === 'diff') {
|
||||
setDiffContents((prev) => {
|
||||
if (!prev[file.id]) {
|
||||
@@ -152,6 +154,10 @@ export function useEditorPanelContentState({
|
||||
})
|
||||
return
|
||||
}
|
||||
// Why: the WSL retry may already have reloaded it when the host turned ready; a second read would flash.
|
||||
if (options?.onlyIfFailed && !fileContentsRef.current[file.id]?.loadError) {
|
||||
return
|
||||
}
|
||||
delete fileLoadRetryAttemptsRef.current[file.id]
|
||||
setFileContents((prev) => {
|
||||
if (!prev[file.id]) {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateAction } from 'react'
|
||||
import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
import { useWorktreeHostConnection } from '@/lib/workspace/ownership/worktree-host-connection-phase'
|
||||
import { selectWorkspaceRuntimeEnvironmentId } from '@/lib/workspace/ownership/workspace-runtime-environment'
|
||||
import { useAppStateValue } from '@/store/retained-views/app-state-view'
|
||||
import type { WslHostConnectionState } from '../../../../shared/wsl-host-types'
|
||||
import { displayIpcErrorMessage } from '@/runtime/errors/ipc-error'
|
||||
import { hasRuntimeRpcErrorCode } from '../../../../shared/runtime-rpc-error-code'
|
||||
import { isFileTooLargeMessage } from '../../../../shared/file-write/file-write-disk-precondition'
|
||||
@@ -60,6 +63,25 @@ export function shouldRetryFileLoadError(message: string, code?: string): boolea
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* A WSL host's connection in the SSH phase's terms, so a read that failed while it was down waits
|
||||
* for it and retries once it answers. Null for any other host.
|
||||
*/
|
||||
export function wslHostRetryConnection(
|
||||
environmentId: string | null,
|
||||
state: WslHostConnectionState | undefined
|
||||
): { targetId: string; connecting: boolean; connectedEpoch: string | null } | null {
|
||||
if (!environmentId || state === undefined) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
targetId: `wsl:${environmentId}`,
|
||||
connecting: state === 'connecting' || state === 'reconnecting',
|
||||
// Per host, not per connection: main publishes connecting before every ready, which re-arms it.
|
||||
connectedEpoch: state === 'ready' ? `wsl:${environmentId}` : null
|
||||
}
|
||||
}
|
||||
|
||||
export function useEditorPanelFileLoadRetry({
|
||||
activeFile,
|
||||
fileContents,
|
||||
@@ -76,9 +98,18 @@ export function useEditorPanelFileLoadRetry({
|
||||
? fileContents[activeFileLoadRetryId]?.loadErrorCode
|
||||
: undefined
|
||||
const hostConnection = useWorktreeHostConnection(activeFile?.worktreeId ?? null)
|
||||
const hostTargetId = hostConnection.targetId
|
||||
const hostConnecting = hostConnection.phase === 'connecting'
|
||||
const connectedHostEpoch = hostConnection.connectedEpoch
|
||||
const wslEnvironmentId = useAppStateValue((state) =>
|
||||
selectWorkspaceRuntimeEnvironmentId(state, activeFile?.worktreeId)
|
||||
)
|
||||
const wslHostState = useAppStateValue((state) =>
|
||||
wslEnvironmentId ? state.wslHostStatuses[wslEnvironmentId]?.state : undefined
|
||||
)
|
||||
// An SSH target keeps its own signal; only a workspace with none reads its WSL host.
|
||||
const wslHost =
|
||||
hostConnection.phase === 'local' ? wslHostRetryConnection(wslEnvironmentId, wslHostState) : null
|
||||
const hostTargetId = wslHost?.targetId ?? hostConnection.targetId
|
||||
const hostConnecting = wslHost?.connecting ?? hostConnection.phase === 'connecting'
|
||||
const connectedHostEpoch = wslHost ? wslHost.connectedEpoch : hostConnection.connectedEpoch
|
||||
const seenHostRef = useRef({ targetId: hostTargetId, connectedEpoch: connectedHostEpoch })
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, useRef, useState } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { OpenFile } from '@/store/slices/editor/types/open-file'
|
||||
import type { WslHostConnectionState } from '../../../../shared/wsl-host-types'
|
||||
import type { FileContent } from './editor-panel-content-types'
|
||||
|
||||
const host = vi.hoisted((): { state: string | undefined } => ({ state: undefined }))
|
||||
|
||||
vi.mock(
|
||||
'@/lib/workspace/ownership/worktree-host-connection-phase',
|
||||
() => import('./local-host-test-fixture')
|
||||
)
|
||||
vi.mock('@/lib/workspace/ownership/workspace-runtime-environment', () => ({
|
||||
selectWorkspaceRuntimeEnvironmentId: () => 'wsl-env'
|
||||
}))
|
||||
vi.mock('@/store/retained-views/app-state-view', () => ({
|
||||
useAppStateValue: <T,>(select: (state: unknown) => T): T =>
|
||||
select({
|
||||
wslHostStatuses: host.state
|
||||
? { 'wsl-env': { environmentId: 'wsl-env', distro: 'demo', state: host.state } }
|
||||
: {}
|
||||
})
|
||||
}))
|
||||
|
||||
import { useEditorPanelFileLoadRetry, wslHostRetryConnection } from './useEditorPanelFileLoadRetry'
|
||||
|
||||
const FILE: OpenFile = {
|
||||
id: 'file-1',
|
||||
filePath: '/home/orca/demo/app/main.go',
|
||||
relativePath: 'main.go',
|
||||
worktreeId: 'repo::/home/orca/demo/app',
|
||||
language: 'go',
|
||||
isDirty: false,
|
||||
mode: 'edit'
|
||||
}
|
||||
const UNREACHABLE = 'Could not connect to the remote Orca runtime.'
|
||||
|
||||
function Probe({ loadFileContent }: { loadFileContent: () => Promise<void> }): null {
|
||||
const [fileContents, setFileContents] = useState<Record<string, FileContent>>({
|
||||
[FILE.id]: { content: '', isBinary: false, loadError: UNREACHABLE }
|
||||
})
|
||||
const openFilesRef = useRef([FILE])
|
||||
const fileLoadRetryAttemptsRef = useRef<Record<string, number>>({ [FILE.id]: 3 })
|
||||
useEditorPanelFileLoadRetry({
|
||||
activeFile: FILE,
|
||||
fileContents,
|
||||
fileLoadRetryAttemptsRef,
|
||||
loadFileContent,
|
||||
openFilesRef,
|
||||
setFileContents
|
||||
})
|
||||
return null
|
||||
}
|
||||
|
||||
describe('useEditorPanelFileLoadRetry on a WSL host', () => {
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
container = document.createElement('div')
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
const render = (loadFileContent: () => Promise<void>): void =>
|
||||
act(() => root.render(<Probe loadFileContent={loadFileContent} />))
|
||||
|
||||
it('waits while the host connects, then reloads once it answers', async () => {
|
||||
const loadFileContent = vi.fn(async () => {})
|
||||
host.state = 'connecting'
|
||||
render(loadFileContent)
|
||||
await act(async () => {
|
||||
await vi.advanceTimersByTimeAsync(10_000)
|
||||
})
|
||||
expect(loadFileContent).not.toHaveBeenCalled()
|
||||
|
||||
host.state = 'ready'
|
||||
render(loadFileContent)
|
||||
expect(loadFileContent).toHaveBeenCalledWith(
|
||||
FILE.filePath,
|
||||
FILE.id,
|
||||
FILE.worktreeId,
|
||||
FILE.relativePath
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('wslHostRetryConnection', () => {
|
||||
it.each<[WslHostConnectionState, boolean, string | null]>([
|
||||
['connecting', true, null],
|
||||
['reconnecting', true, null],
|
||||
['ready', false, 'wsl:env-1'],
|
||||
['distro-stopped', false, null],
|
||||
['failed', false, null]
|
||||
])('%s', (state, connecting, connectedEpoch) => {
|
||||
expect(wslHostRetryConnection('env-1', state)).toEqual({
|
||||
targetId: 'wsl:env-1',
|
||||
connecting,
|
||||
connectedEpoch
|
||||
})
|
||||
})
|
||||
|
||||
it('is null for a host that is not a WSL host', () => {
|
||||
expect(wslHostRetryConnection(null, undefined)).toBeNull()
|
||||
expect(wslHostRetryConnection('ssh-env', undefined)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -66,6 +66,7 @@ import { useEditorPanelContentState } from './useEditorPanelContentState'
|
||||
import { FILE_LOAD_RETRY_DELAYS_MS } from './useEditorPanelFileLoadRetry'
|
||||
|
||||
let latestFileContents: Record<string, FileContent> = {}
|
||||
let latestReload: ReturnType<typeof useEditorPanelContentState>['reloadContent'] = () => {}
|
||||
|
||||
const EMPTY_EDITOR_VIEW_MODE = {}
|
||||
const HOST_READ_LATENCY_MS = 1
|
||||
@@ -80,6 +81,7 @@ function Probe({ activeFile, openFiles }: { activeFile: OpenFile; openFiles: Ope
|
||||
editorViewMode: EMPTY_EDITOR_VIEW_MODE
|
||||
})
|
||||
latestFileContents = state.fileContents
|
||||
latestReload = state.reloadContent
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -189,4 +191,53 @@ describe('useEditorPanelContentState — host cannot resolve a mirrored file (#2
|
||||
await advanceTimers(60_000)
|
||||
expect(closeFile).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('skips a reload after Start when the file already loaded, and reloads one still failed', async () => {
|
||||
const activeFile = { ...makeDirtyMirroredFile(), isDirty: false }
|
||||
const openFiles = [activeFile]
|
||||
const store = createTestStore()
|
||||
store.setState({
|
||||
openFiles,
|
||||
worktreesByRepo: {
|
||||
project: [
|
||||
makeWorktree({
|
||||
id: activeFile.worktreeId,
|
||||
repoId: 'project',
|
||||
path: '/home/user/project',
|
||||
hostId: 'runtime:env-1'
|
||||
})
|
||||
]
|
||||
},
|
||||
setLastKnownDiskSignature: vi.fn()
|
||||
})
|
||||
mocks.getState.mockImplementation(store.getState)
|
||||
mocks.readRuntimeFileContent.mockResolvedValue({ content: '# notes', isBinary: false })
|
||||
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
await act(async () => {
|
||||
root?.render(<Probe activeFile={activeFile} openFiles={openFiles} />)
|
||||
})
|
||||
await advanceTimers(HOST_READ_LATENCY_MS)
|
||||
expect(latestFileContents[activeFile.id]?.content).toBe('# notes')
|
||||
const readsAfterLoad = mocks.readRuntimeFileContent.mock.calls.length
|
||||
|
||||
await act(async () => latestReload(activeFile, { onlyIfFailed: true }))
|
||||
await advanceTimers(HOST_READ_LATENCY_MS)
|
||||
expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(readsAfterLoad)
|
||||
expect(latestFileContents[activeFile.id]?.content).toBe('# notes')
|
||||
|
||||
// A non-retryable failure keeps the editor's own retry out of the count.
|
||||
mocks.readRuntimeFileContent.mockRejectedValueOnce(new Error('ENOENT: no such file'))
|
||||
await act(async () => latestReload(activeFile))
|
||||
await advanceTimers(HOST_READ_LATENCY_MS)
|
||||
expect(latestFileContents[activeFile.id]?.loadError).toContain('ENOENT')
|
||||
expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(readsAfterLoad + 1)
|
||||
|
||||
await act(async () => latestReload(activeFile, { onlyIfFailed: true }))
|
||||
await advanceTimers(HOST_READ_LATENCY_MS)
|
||||
expect(mocks.readRuntimeFileContent).toHaveBeenCalledTimes(readsAfterLoad + 2)
|
||||
expect(latestFileContents[activeFile.id]?.content).toBe('# notes')
|
||||
})
|
||||
})
|
||||
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import type { DiscoveredSkill, SkillDiscoveryResult } from '../../../../../../shared/skills'
|
||||
import { useAppStore } from '@/store'
|
||||
import { makeFolderWorkspace } from '@/store/folder-workspaces/folder-workspace.test-fixture'
|
||||
import { useNativeChatSkills } from './use-native-chat-skills'
|
||||
|
||||
const rpc = vi.hoisted(() => ({ discover: vi.fn() }))
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc.discover }))
|
||||
vi.mock('@/store', async () => {
|
||||
const { createTestStore } = await import('@/store/testing/app-store-test-fixture')
|
||||
return { useAppStore: createTestStore() }
|
||||
})
|
||||
|
||||
const SKILLS_ROOT = '/home/user/.agents/skills'
|
||||
let installed: string[]
|
||||
let tabId: string
|
||||
|
||||
beforeEach(() => {
|
||||
installed = []
|
||||
useAppStore.setState(useAppStore.getInitialState(), true)
|
||||
useAppStore.setState({
|
||||
folderWorkspaces: [makeFolderWorkspace({ id: 'skills', folderPath: '/home/user/project' })]
|
||||
})
|
||||
tabId = useAppStore.getState().createUnifiedTab('folder:skills', 'agent-session', {
|
||||
agentSessionAgent: 'codex',
|
||||
executionHostId: 'local'
|
||||
}).id
|
||||
rpc.discover.mockReset().mockImplementation(async () => inventory())
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
function inventory(): SkillDiscoveryResult {
|
||||
const skills = installed.map((name): DiscoveredSkill => ({
|
||||
id: name,
|
||||
name,
|
||||
description: null,
|
||||
providers: ['agent-skills'],
|
||||
sourceKind: 'home',
|
||||
sourceLabel: 'Shared',
|
||||
rootPath: SKILLS_ROOT,
|
||||
directoryPath: `${SKILLS_ROOT}/${name}`,
|
||||
skillFilePath: `${SKILLS_ROOT}/${name}/SKILL.md`,
|
||||
installed: true,
|
||||
updatedAt: null
|
||||
}))
|
||||
const source = {
|
||||
id: 'shared',
|
||||
label: 'Shared',
|
||||
path: SKILLS_ROOT,
|
||||
sourceKind: 'home' as const,
|
||||
providers: ['agent-skills' as const],
|
||||
owner: null,
|
||||
exists: true
|
||||
}
|
||||
return { skills, sources: [source], scannedAt: 0 }
|
||||
}
|
||||
|
||||
it('discovers a newly installed global skill when the same chat reopens its picker', async () => {
|
||||
const { result, rerender } = renderHook(
|
||||
(open: boolean) => useNativeChatSkills('codex', tabId, open),
|
||||
{ initialProps: true }
|
||||
)
|
||||
await waitFor(() => expect(result.current.status).toBe('ready'))
|
||||
expect(result.current.skills).toEqual([])
|
||||
rerender(false)
|
||||
installed.push('installed-later')
|
||||
rerender(true)
|
||||
// Reopening shows the last answer while the host is asked again, not a loading flash.
|
||||
expect(result.current.status).toBe('ready')
|
||||
await waitFor(() =>
|
||||
expect(result.current.skills.map((skill) => skill.name)).toEqual(['installed-later'])
|
||||
)
|
||||
})
|
||||
|
||||
it('does not restore a closed picker snapshot when its pending scan finishes', async () => {
|
||||
const release = Promise.withResolvers<SkillDiscoveryResult>()
|
||||
rpc.discover.mockImplementationOnce(() => release.promise)
|
||||
const { result, rerender } = renderHook(
|
||||
(open: boolean) => useNativeChatSkills('codex', tabId, open),
|
||||
{ initialProps: true }
|
||||
)
|
||||
const beforeInstall = inventory()
|
||||
rerender(false)
|
||||
installed.push('installed-later')
|
||||
await act(async () => {
|
||||
release.resolve(beforeInstall)
|
||||
await release.promise
|
||||
})
|
||||
rerender(true)
|
||||
await waitFor(() =>
|
||||
expect(result.current.skills.map((skill) => skill.name)).toEqual(['installed-later'])
|
||||
)
|
||||
})
|
||||
@@ -80,7 +80,10 @@ export function useNativeChatSkills(
|
||||
)
|
||||
const [state, setState] = useState<StoredDiscoveryState>(IDLE_STATE)
|
||||
const [retryGeneration, setRetryGeneration] = useState(0)
|
||||
// Last answer per pane, shown at once on reopen while the host is asked again.
|
||||
const paneDiscoveryCache = useRef(new Map<string, SkillDiscoveryResult>())
|
||||
// Panes already asked during this open; store churn re-runs the effect and must not re-query.
|
||||
const checkedThisOpen = useRef(new Set<string>())
|
||||
// Consume retry intent once; a generation-wide force flag would leak across pane switches.
|
||||
const forceNextDiscovery = useRef(false)
|
||||
const profile = getNativeChatAgentProfile(agent)
|
||||
@@ -90,6 +93,8 @@ export function useNativeChatSkills(
|
||||
if (!profile || !enabled || !context) {
|
||||
// Without a current pane, discard retry intent before it can force another pane’s scan.
|
||||
forceNextDiscovery.current = false
|
||||
// The next open asks the host again so skills installed meanwhile appear.
|
||||
checkedThisOpen.current.clear()
|
||||
setState(IDLE_STATE)
|
||||
return
|
||||
}
|
||||
@@ -111,16 +116,19 @@ export function useNativeChatSkills(
|
||||
|
||||
const paneCacheKey = context.key
|
||||
const cached = paneDiscoveryCache.current.get(paneCacheKey)
|
||||
if (cached) {
|
||||
setState(
|
||||
cached
|
||||
? { status: 'ready', skills: cached.skills, error: null, contextKey: context.key }
|
||||
: { status: 'loading', skills: [], error: null, contextKey: context.key }
|
||||
)
|
||||
if (cached && checkedThisOpen.current.has(paneCacheKey)) {
|
||||
emitNativeChatSkillDiscovery({
|
||||
agent,
|
||||
outcome: 'ready',
|
||||
executionHostKind: context.executionHostKind
|
||||
})
|
||||
setState({ status: 'ready', skills: cached.skills, error: null, contextKey: context.key })
|
||||
return
|
||||
}
|
||||
setState({ status: 'loading', skills: [], error: null, contextKey: context.key })
|
||||
// Explicit Retry bypasses shared host scans; passive discovery reuses them.
|
||||
const forced = forceNextDiscovery.current
|
||||
forceNextDiscovery.current = false
|
||||
@@ -128,9 +136,11 @@ export function useNativeChatSkills(
|
||||
void request.then(
|
||||
(result) => {
|
||||
paneDiscoveryCache.current.set(paneCacheKey, result)
|
||||
// A scan that settles after close still seeds the next open but must not count as its check.
|
||||
if (cancelled) {
|
||||
return
|
||||
}
|
||||
checkedThisOpen.current.add(paneCacheKey)
|
||||
emitNativeChatSkillDiscovery({
|
||||
agent,
|
||||
outcome: 'ready',
|
||||
@@ -149,6 +159,11 @@ export function useNativeChatSkills(
|
||||
outcome: timedOut ? 'timeout' : 'error',
|
||||
executionHostKind: context.executionHostKind
|
||||
})
|
||||
checkedThisOpen.current.add(paneCacheKey)
|
||||
if (cached) {
|
||||
// A failed recheck keeps the last good list rather than hiding it behind an error.
|
||||
return
|
||||
}
|
||||
setState({
|
||||
status: 'error',
|
||||
skills: [],
|
||||
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import { cleanup, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { render } from '../../messages/actions/native-chat-tooltip-test-harness'
|
||||
import { NativeChatMessageList } from '../../NativeChatMessageList'
|
||||
import {
|
||||
layout,
|
||||
marker,
|
||||
session,
|
||||
stubLayout,
|
||||
stubResizeObserver
|
||||
} from '../../viewport/virtualization/native-chat-windowing-test-harness'
|
||||
|
||||
// Pacing is not this test's subject.
|
||||
vi.mock('../../markdown/use-native-chat-paced-text', async (importOriginal) =>
|
||||
(await import('../../markdown/native-chat-unpaced-text-fixture')).unpacedTextModule(
|
||||
importOriginal
|
||||
)
|
||||
)
|
||||
|
||||
let restore: (() => void)[] = []
|
||||
beforeEach(() => {
|
||||
restore = [stubLayout({ scrollGeometry: true, offsetChain: true }), stubResizeObserver()]
|
||||
})
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
for (const undo of restore.toReversed()) {
|
||||
undo()
|
||||
}
|
||||
layout.measuredRowHeights = []
|
||||
})
|
||||
|
||||
it('draws a worker approval at its own time, with newer replies after it', () => {
|
||||
// marker(i) is message `marker-i`, at time i + 1.
|
||||
const messages = [0, 1, 2, 3].map(marker)
|
||||
render(
|
||||
<NativeChatMessageList
|
||||
session={session(messages)}
|
||||
isWorking={false}
|
||||
expandSignal={false}
|
||||
timedRows={[
|
||||
{ key: 'open', at: 3.5, node: <p>Allow Bash? (open)</p> },
|
||||
{ key: 'receipt', at: 1.5, node: <p>Allowed by you 3:11 PM</p> }
|
||||
]}
|
||||
/>
|
||||
)
|
||||
|
||||
const order = [
|
||||
'marker-0',
|
||||
'Allowed by you 3:11 PM',
|
||||
'marker-1',
|
||||
'marker-2',
|
||||
'Allow Bash? (open)',
|
||||
'marker-3'
|
||||
].map((text) => screen.getByText(text))
|
||||
for (const [index, element] of order.slice(1).entries()) {
|
||||
expect(order[index].compareDocumentPosition(element)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
|
||||
}
|
||||
})
|
||||
-86
@@ -1,86 +0,0 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import '@testing-library/jest-dom/vitest'
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import { afterEach, expect, it, vi } from 'vitest'
|
||||
import type { OrchestrationCrewRow } from '../../../../../shared/orchestration/orchestration-crew'
|
||||
|
||||
const rpc = vi.hoisted(() => ({ call: vi.fn() }))
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), info: vi.fn(), error: vi.fn() }))
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: rpc.call }))
|
||||
vi.mock('sonner', () => ({ toast }))
|
||||
|
||||
const { RuntimeRpcCallError } = await import('@/runtime/rpc/calls/runtime-rpc-result')
|
||||
const { NativeChatWorkerApprovalStack } = await import('./NativeChatWorkerApprovals')
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
const worker: OrchestrationCrewRow = {
|
||||
partyKey: 'w',
|
||||
role: 'worker',
|
||||
label: 'try-claude',
|
||||
agentKind: 'claude',
|
||||
status: 'blocked'
|
||||
}
|
||||
const entry = {
|
||||
approval: {
|
||||
v: 1 as const,
|
||||
approvalId: 'apr_1',
|
||||
state: 'open' as const,
|
||||
worker: { handle: 'term_w', dispatchId: 'ctx_1', taskId: 'task_1' },
|
||||
summary: { title: 'Allow Bash?', detail: 'rg -n x', reason: null },
|
||||
allowedActions: ['allow' as const, 'deny' as const]
|
||||
},
|
||||
at: '2026-11-11T20:11:30.000Z',
|
||||
askedAt: '2026-11-11T20:11:24.000Z',
|
||||
worker
|
||||
}
|
||||
|
||||
const reject = (code: string) =>
|
||||
rpc.call.mockRejectedValueOnce(
|
||||
new RuntimeRpcCallError({
|
||||
id: '1',
|
||||
ok: false,
|
||||
error: { code, message: code },
|
||||
_meta: { runtimeId: 'r' }
|
||||
})
|
||||
)
|
||||
|
||||
function renderStack() {
|
||||
render(<NativeChatWorkerApprovalStack approvals={[entry]} target={{ kind: 'local' }} />)
|
||||
}
|
||||
|
||||
it('waits on the host after a click: both buttons off, the clicked one working, no toast when it lands', async () => {
|
||||
renderStack()
|
||||
let land: (value: unknown) => void = () => {}
|
||||
rpc.call.mockReturnValueOnce(new Promise((resolve) => (land = resolve)))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
|
||||
expect(screen.getByRole('button', { name: 'Allow' })).toBeDisabled()
|
||||
expect(screen.getByRole('button', { name: 'Deny' })).toBeDisabled()
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'Allow' }).querySelector('.animate-spin')
|
||||
).not.toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'Deny' }).querySelector('.animate-spin')).toBeNull()
|
||||
land({})
|
||||
await waitFor(() => expect(screen.getByRole('button', { name: 'Allow' })).toBeEnabled())
|
||||
expect(toast.success).not.toHaveBeenCalled()
|
||||
expect(toast.info).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves the card to the host list when the answer was not applied', async () => {
|
||||
renderStack()
|
||||
reject('approval_not_open')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Allow' }))
|
||||
await waitFor(() => expect(toast.info).toHaveBeenCalledTimes(1))
|
||||
// Still open as far as this card knows: answerable again until the host's list says otherwise.
|
||||
expect(screen.getByRole('button', { name: 'Allow' })).toBeEnabled()
|
||||
|
||||
reject('internal_error')
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Deny' }))
|
||||
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1))
|
||||
expect(screen.getByRole('button', { name: 'Deny' })).toBeEnabled()
|
||||
})
|
||||
-9
@@ -82,12 +82,3 @@ it('keeps a prompt that closed while shown pinned as its receipt for a moment, t
|
||||
expect(pinned.result.current).toEqual([])
|
||||
expect(receipts.result.current.map((e) => e.approval.approvalId)).toEqual(['apr_old', 'apr_1'])
|
||||
})
|
||||
|
||||
it('keeps a prompt only the worker terminal can answer pinned', async () => {
|
||||
vi.useFakeTimers()
|
||||
const pinned = renderHook(() => feed.useNativeChatPinnedWorkerApprovals('orca_session_id:other'))
|
||||
await act(async () => {})
|
||||
send(approval('apr_t', 'answered', 'terminal-only'))
|
||||
act(() => vi.advanceTimersByTime(60_000))
|
||||
expect(pinned.result.current.map((e) => e.approval.approvalId)).toEqual(['apr_t'])
|
||||
})
|
||||
|
||||
@@ -41,7 +41,7 @@ import { useFileExplorerBackgroundMenu } from './use-file-explorer-background-me
|
||||
import { useFileExplorerNameFilter } from './use-file-explorer-name-filter'
|
||||
import { useFileExplorerTreePaneState } from '../tree/use-file-explorer-tree-pane-state'
|
||||
import { useWslHostUnavailableReason } from '../../../../runtime/hosts/wsl/wsl-host-availability'
|
||||
import { useStoppedWslHost } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { useWslHostReadOutage } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { useUiLanguageRevision } from '@/i18n/use-ui-language-revision'
|
||||
|
||||
@@ -57,7 +57,7 @@ function FileExplorerFiles(): React.JSX.Element {
|
||||
runtimeEnvironmentIdOrLocalUnlessTwin(s, activeWorktreeId)
|
||||
)
|
||||
const wslHostUnavailable = useWslHostUnavailableReason(activeWorktreeId)
|
||||
const stoppedWslHost = useStoppedWslHost(activeWorktreeId)
|
||||
const stoppedWslHost = useWslHostReadOutage(activeWorktreeId)
|
||||
const activeWorktree = useActiveWorktree()
|
||||
const activeRepo = useRepoById(activeWorktree?.repoId ?? null)
|
||||
// Why: a folder workspace has no repo row, so only the catalog owner names its SSH host.
|
||||
|
||||
+2
-2
@@ -17,7 +17,7 @@ import type { useFileExplorerSelection } from '../selection/useFileExplorerSelec
|
||||
import type { useFileExplorerTree } from './useFileExplorerTree'
|
||||
import type { useFileExplorerTreePaneState } from './use-file-explorer-tree-pane-state'
|
||||
import type { WslHostUnavailableReason } from '../../../../runtime/hosts/wsl/wsl-host-availability'
|
||||
import type { StoppedWslHost } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import type { WslHostReadOutage } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
|
||||
type FileExplorerFilesTreePaneProps = {
|
||||
activeRepo: Repo | null
|
||||
@@ -39,7 +39,7 @@ type FileExplorerFilesTreePaneProps = {
|
||||
handleExplorerBackgroundContextMenuCapture: (event: React.MouseEvent<HTMLDivElement>) => void
|
||||
handleExplorerBackgroundDoubleClick: (event: React.MouseEvent<HTMLDivElement>) => void
|
||||
wslHostUnavailable?: WslHostUnavailableReason | null
|
||||
stoppedWslHost?: StoppedWslHost | null
|
||||
stoppedWslHost?: WslHostReadOutage | null
|
||||
}
|
||||
|
||||
export function FileExplorerFilesTreePane({
|
||||
|
||||
+4
-3
@@ -7,7 +7,7 @@ import {
|
||||
getWslHostsTurnedOffLabel,
|
||||
getWslHostsTurnOnLabel
|
||||
} from '../../../sidebar/wsl-host-row-status'
|
||||
import type { StoppedWslHost } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import type { WslHostReadOutage } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { WslHostStoppedNotice } from '../../../wsl-host-stopped/WslHostStoppedNotice'
|
||||
|
||||
type FileExplorerTreeStatusProps = {
|
||||
@@ -18,8 +18,8 @@ type FileExplorerTreeStatusProps = {
|
||||
emptyMessage?: string
|
||||
/** The workspace's WSL host is turned off: offer the switch instead of a read error. */
|
||||
wslHostsTurnedOff?: boolean
|
||||
/** The workspace's WSL host is stopped: offer Start instead of a read error. */
|
||||
stoppedWslHost?: StoppedWslHost | null
|
||||
/** The workspace's WSL host is stopped or still connecting: its notice instead of a read error. */
|
||||
stoppedWslHost?: WslHostReadOutage | null
|
||||
onWslHostStarted?: () => void
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ export function FileExplorerTreeStatus({
|
||||
<WslHostStoppedNotice
|
||||
environmentId={stoppedWslHost.environmentId}
|
||||
distro={stoppedWslHost.distro}
|
||||
connecting={stoppedWslHost.connecting}
|
||||
className="h-full text-[11px]"
|
||||
onStarted={onWslHostStarted}
|
||||
/>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { ConflictSummaryCard, OperationBanner } from './conflict-status-cards'
|
||||
import { EmptyState } from './empty-state'
|
||||
import { StatusRetryButton } from './status-retry-button'
|
||||
import { TooManyChangesBanner } from './too-many-changes-banner'
|
||||
import { useStoppedWslHost } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { useWslHostReadOutage } from '../../../wsl-host-stopped/use-stopped-wsl-host'
|
||||
import { WslHostStoppedNotice } from '../../../wsl-host-stopped/WslHostStoppedNotice'
|
||||
import { useSourceControlScope } from '../panel/worktree-scope'
|
||||
import { shortRefLabel } from '../../../../../../shared/source-control/short-ref-label'
|
||||
@@ -62,8 +62,8 @@ export function SourceControlContentStatus({
|
||||
filterQuery: string
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
// Why: a stopped host can't answer git, so its read error or "clean" result is not the workspace's.
|
||||
const stoppedWslHost = useStoppedWslHost(worktreeId)
|
||||
// Why: a stopped or still-connecting host can't answer git, so its read error or "clean" result is not the workspace's.
|
||||
const stoppedWslHost = useWslHostReadOutage(worktreeId)
|
||||
// Folder sections keep to the plain message and Retry; raw Git output stays in the worktree's own panel.
|
||||
const showRawStatusError = useSourceControlScope() === null
|
||||
return (
|
||||
@@ -72,6 +72,7 @@ export function SourceControlContentStatus({
|
||||
<WslHostStoppedNotice
|
||||
environmentId={stoppedWslHost.environmentId}
|
||||
distro={stoppedWslHost.distro}
|
||||
connecting={stoppedWslHost.connecting}
|
||||
className="py-6 text-xs"
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
vi.mock('@/runtime/hosts/wsl/wsl-host-user-start', () => ({
|
||||
startWslHostAndReloadProjects: vi.fn(async () => true)
|
||||
}))
|
||||
|
||||
import { WslHostStoppedNotice } from './WslHostStoppedNotice'
|
||||
|
||||
describe('WslHostStoppedNotice', () => {
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => act(() => root.unmount()))
|
||||
|
||||
it('offers Start while the host is stopped', () => {
|
||||
act(() => root.render(<WslHostStoppedNotice environmentId="env" distro="demo" />))
|
||||
expect(container.textContent).toContain('demo is stopped')
|
||||
expect(container.querySelector('button')?.textContent).toBe('Start')
|
||||
})
|
||||
|
||||
it('shows Connecting with no Start while the host boots', () => {
|
||||
act(() => root.render(<WslHostStoppedNotice environmentId="env" distro="demo" connecting />))
|
||||
expect(container.textContent).toContain('Connecting to demo…')
|
||||
expect(container.querySelector('[data-wsl-host-connecting]')).not.toBeNull()
|
||||
expect(container.querySelector('button')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,22 +1,27 @@
|
||||
import React, { useState } from 'react'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { LoadingSpinner } from '@/components/LoadingSpinner'
|
||||
import { LinuxPenguinIcon } from '@/components/icons/LinuxPenguinIcon'
|
||||
import { useMountedRef } from '@/hooks/useMountedRef'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { cn } from '@/lib/class-names'
|
||||
import { startWslHostAndReloadProjects } from '@/runtime/hosts/wsl/wsl-host-user-start'
|
||||
|
||||
/** "<distro> is stopped" with Start, where a surface would otherwise show a read error. Only the click boots (E9). */
|
||||
/**
|
||||
* "<distro> is stopped" with Start, where a surface would otherwise show a read error. Only the click
|
||||
* boots (E9). `connecting` swaps in "Connecting to <distro>…" while it boots, so the stale error never shows.
|
||||
*/
|
||||
export function WslHostStoppedNotice({
|
||||
environmentId,
|
||||
distro,
|
||||
connecting = false,
|
||||
size = 'xs',
|
||||
className,
|
||||
onStarted
|
||||
}: {
|
||||
environmentId: string
|
||||
distro: string
|
||||
connecting?: boolean
|
||||
size?: 'xs' | 'sm'
|
||||
className?: string
|
||||
onStarted?: () => void
|
||||
@@ -48,15 +53,26 @@ export function WslHostStoppedNotice({
|
||||
className="mb-1 size-7 text-muted-foreground"
|
||||
data-wsl-host-stopped-icon=""
|
||||
/>
|
||||
<span>
|
||||
{t('components.native-chat.hostOutage.stopped', '{{distro}} is stopped', {
|
||||
distro
|
||||
})}
|
||||
</span>
|
||||
<Button type="button" size={size} disabled={starting} onClick={start}>
|
||||
{starting ? <Loader2 className="animate-spin" /> : null}
|
||||
{t('components.native-chat.hostOutage.start', 'Start')}
|
||||
</Button>
|
||||
{connecting ? (
|
||||
<span className="flex items-center gap-1.5" data-wsl-host-connecting="">
|
||||
<LoadingSpinner className="size-4" />
|
||||
{t('components.native-chat.hostOutage.connecting', 'Connecting to {{distro}}…', {
|
||||
distro
|
||||
})}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span>
|
||||
{t('components.native-chat.hostOutage.stopped', '{{distro}} is stopped', {
|
||||
distro
|
||||
})}
|
||||
</span>
|
||||
<Button type="button" size={size} disabled={starting} onClick={start}>
|
||||
{starting ? <LoadingSpinner /> : null}
|
||||
{t('components.native-chat.hostOutage.start', 'Start')}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
import { useAppStateValue } from '@/store/retained-views/app-state-view'
|
||||
import { useMemo } from 'react'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { selectStoppedWslDistro } from '@/runtime/hosts/wsl/wsl-host-stopped-status'
|
||||
import {
|
||||
selectConnectingWslDistro,
|
||||
selectStoppedWslDistro
|
||||
} from '@/runtime/hosts/wsl/wsl-host-stopped-status'
|
||||
import { selectWorkspaceRuntimeEnvironmentId } from '../../lib/workspace/ownership/workspace-runtime-environment'
|
||||
import { selectWslHostEnvironmentUnavailableReason } from '../../runtime/hosts/wsl/wsl-host-availability'
|
||||
|
||||
export type StoppedWslHost = { environmentId: string; distro: string }
|
||||
/** A host a read surface waits on instead of showing its read error; `connecting` once Start (or a reconnect) is under way. */
|
||||
export type WslHostReadOutage = StoppedWslHost & { connecting: boolean }
|
||||
|
||||
/** A stopped distro Start can boot; a host that cannot run (turned off, server files missing) keeps its own notice. */
|
||||
export function selectStartableStoppedWslDistro(
|
||||
@@ -40,3 +45,27 @@ export function useStoppedWslHost(worktreeId: string | null | undefined): Stoppe
|
||||
[environmentId, distro]
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* For surfaces that mask a read error: a read that failed while the host was down stays stale
|
||||
* until the host answers, so a connecting host keeps the notice up instead of that error.
|
||||
*/
|
||||
export function useWslHostReadOutage(
|
||||
worktreeId: string | null | undefined
|
||||
): WslHostReadOutage | null {
|
||||
const stopped = useStoppedWslHost(worktreeId)
|
||||
const environmentId = useAppStateValue((state) =>
|
||||
selectWorkspaceRuntimeEnvironmentId(state, worktreeId)
|
||||
)
|
||||
const connectingDistro = useAppStateValue((state) =>
|
||||
selectConnectingWslDistro(state, environmentId)
|
||||
)
|
||||
return useMemo(() => {
|
||||
if (stopped) {
|
||||
return { ...stopped, connecting: false }
|
||||
}
|
||||
return environmentId && connectingDistro
|
||||
? { environmentId, distro: connectingDistro, connecting: true }
|
||||
: null
|
||||
}, [stopped, environmentId, connectingDistro])
|
||||
}
|
||||
|
||||
@@ -21169,6 +21169,7 @@
|
||||
"reconnect": "Reconnect",
|
||||
"stopped": "{{distro}} is stopped",
|
||||
"start": "Start",
|
||||
"connecting": "Connecting to {{distro}}…",
|
||||
"startFailed": "Couldn’t start {{distro}}. Check it in Settings → Remote Orca Servers.",
|
||||
"unverifiable": "Orca couldn't check whether {{distro}} is running",
|
||||
"startToSend": "Start {{distro}} to send.",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { WslHostConnectionState } from '../../../../../shared/wsl-host-types'
|
||||
import { selectConnectingWslDistro, selectStoppedWslDistro } from './wsl-host-stopped-status'
|
||||
|
||||
const stateWith = (state: WslHostConnectionState) => ({
|
||||
wslHostStatuses: { env: { environmentId: 'env', distro: 'demo', state, detail: null } }
|
||||
})
|
||||
|
||||
describe('selectConnectingWslDistro', () => {
|
||||
it.each<[WslHostConnectionState, string | null]>([
|
||||
['connecting', 'demo'],
|
||||
['reconnecting', 'demo'],
|
||||
['ready', null],
|
||||
['distro-stopped', null],
|
||||
['failed', null]
|
||||
])('%s', (state, expected) => {
|
||||
expect(selectConnectingWslDistro(stateWith(state), 'env')).toBe(expected)
|
||||
})
|
||||
|
||||
it('is null for an unknown host and never overlaps stopped', () => {
|
||||
expect(selectConnectingWslDistro(stateWith('connecting'), 'other')).toBeNull()
|
||||
expect(selectConnectingWslDistro(stateWith('connecting'), null)).toBeNull()
|
||||
expect(selectStoppedWslDistro(stateWith('connecting'), 'env')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,15 @@ export function selectStoppedWslDistro(
|
||||
return status?.state === 'distro-stopped' ? status.distro : null
|
||||
}
|
||||
|
||||
/** The distro of a WSL host still connecting, such as after Start while it boots or updates its server. */
|
||||
export function selectConnectingWslDistro(
|
||||
state: Pick<AppState, 'wslHostStatuses'>,
|
||||
environmentId: string | null | undefined
|
||||
): string | null {
|
||||
const status = environmentId ? state.wslHostStatuses[environmentId] : undefined
|
||||
return status?.state === 'connecting' || status?.state === 'reconnecting' ? status.distro : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a pane shows the stopped distro's Start card. A pane whose create failed has no server
|
||||
* yet and is still the workspace's; one on another server, or a host that cannot run, keeps its own
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
/** `agentSession.workState`: the facts a waiter decides from, read without a history page. */
|
||||
export type AgentSessionWorkState = {
|
||||
working: boolean
|
||||
/** A question or approval is waiting for the user. */
|
||||
actionablePrompt: boolean
|
||||
/** Absent = the host makes no queue claim. */
|
||||
queuedMessageIds?: string[]
|
||||
/** With queuedMessageIds, the next unblocked send; null while held. */
|
||||
nextQueuedMessageId?: string | null
|
||||
/** The session's current runtime fence, as history pages state it. */
|
||||
fence?: number
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseCliVersion } from './app-version'
|
||||
|
||||
describe('parseCliVersion', () => {
|
||||
it('reads a version that ends a sentence', () => {
|
||||
expect(
|
||||
parseCliVersion("GitHub Copilot CLI 1.0.109.\nRun 'copilot update' to check for updates.")
|
||||
).toBe('1.0.109')
|
||||
})
|
||||
|
||||
it('rejects a four-part version', () => {
|
||||
expect(parseCliVersion('tool 1.2.3.4')).toBeNull()
|
||||
})
|
||||
})
|
||||
+1
-3
@@ -670,8 +670,7 @@ import {
|
||||
SleepWorkspaceParams,
|
||||
SubscribeTurnCompletionsParams,
|
||||
ThreadGoalParams,
|
||||
UnsubscribeParams,
|
||||
WorkStateParams
|
||||
UnsubscribeParams
|
||||
} from './structured-agent-session-params'
|
||||
import { RespondToQuestionParams } from './structured-agent-session-question-params'
|
||||
import {
|
||||
@@ -880,7 +879,6 @@ export const RPC_PARAMS_BY_METHOD = {
|
||||
'agentSession.subscribeTurnCompletions': SubscribeTurnCompletionsParams,
|
||||
'agentSession.threadGoal': ThreadGoalParams,
|
||||
'agentSession.unsubscribe': UnsubscribeParams,
|
||||
'agentSession.workState': WorkStateParams,
|
||||
'agentSessionAttachment.read': AttachmentReadParams,
|
||||
'agentSessionAttachment.readTextChunk': AttachmentTextReadParams,
|
||||
'agentSessionAttachment.uploadAbort': AttachmentUploadIdParams,
|
||||
|
||||
@@ -335,8 +335,6 @@ export const HistoryParams = z
|
||||
})
|
||||
.strict()
|
||||
|
||||
export const WorkStateParams = z.object({ sessionId: SessionId }).strict()
|
||||
|
||||
// Not strict: an older host ignores these params entirely, and this host must ignore a newer client's.
|
||||
export const SubscribeTurnCompletionsParams = z.object({ includePrompts: z.boolean().optional() })
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { suggestSpeechModel } from './speech-model-suggestion'
|
||||
import type { SpeechModelErrorRate, SpeechModelManifest } from './speech-types'
|
||||
|
||||
const rate = (language: string, percent: number): SpeechModelErrorRate => ({
|
||||
language,
|
||||
percent,
|
||||
metric: 'wer',
|
||||
test: 'fleurs',
|
||||
clips: 5,
|
||||
measuredOn: '2026-11-09'
|
||||
})
|
||||
|
||||
const model = (id: string, extra: Partial<SpeechModelManifest>): SpeechModelManifest => ({
|
||||
id,
|
||||
label: id,
|
||||
type: 'transducer',
|
||||
provider: 'local',
|
||||
language: 'multilingual',
|
||||
languages: [],
|
||||
sampleRate: 16000,
|
||||
streaming: false,
|
||||
...extra
|
||||
})
|
||||
|
||||
const catalog = [
|
||||
model('parakeet', { recommended: true, languages: ['en', 'fr'], errorRates: [rate('fr', 8)] }),
|
||||
model('sense', { languages: ['en', 'ko'], suggestedFor: ['ko'], errorRates: [rate('ko', 10)] }),
|
||||
model('nemotron', { languages: ['fr', 'ko', 'tr'], errorRates: [rate('tr', 14)] }),
|
||||
model('turbo', {
|
||||
languages: ['fr', 'ko', 'tr', 'cy'],
|
||||
errorRates: [rate('fr', 5), rate('ko', 3), rate('tr', 8)]
|
||||
}),
|
||||
model('retired', { languages: ['tr'], errorRates: [rate('tr', 1)], replacedBy: 'turbo' })
|
||||
]
|
||||
|
||||
describe('suggestSpeechModel', () => {
|
||||
it('keeps the user’s own pick while it is offered', () => {
|
||||
const pick = (selectedModelId: string) =>
|
||||
suggestSpeechModel(catalog, 'tr', { selectedModelId, favorAccuracy: false })?.id
|
||||
expect(pick('nemotron')).toBe('nemotron')
|
||||
expect(pick('retired')).toBe('turbo')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user