mirror of
https://github.com/stablyai/orca.git
synced 2026-11-16 02:47:34 +00:00
Merge remote-tracking branch 'origin/main' into brennanb2025/folder-setup-script
This commit is contained in:
@@ -33,7 +33,6 @@ on:
|
||||
- 'src/renderer/src/lib/pane-manager/pane-terminal-output-scheduler-queue-retention.test.ts'
|
||||
- 'src/main/claude-usage/scanner-incremental-append.test.ts'
|
||||
- 'src/main/claude-usage/store-checkpoint-persistence.test.ts'
|
||||
- 'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -264,7 +264,6 @@
|
||||
4 test-no-real-time-wait:src/renderer/src/components/activity/activity-auto-mark-read-loop.react185.test.tsx
|
||||
1 test-no-real-time-wait:src/renderer/src/components/editor/DiagramViewerModal.test.tsx
|
||||
1 test-no-real-time-wait:src/renderer/src/components/editor/combined-diff/load-sections/combined-diff-stale-analysis-work-budget.test.tsx
|
||||
1 test-no-real-time-wait:src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-lifecycle.test.tsx
|
||||
4 test-no-real-time-wait:src/renderer/src/components/native-chat/drafts/native-chat-composer-draft-store.test.ts
|
||||
1 test-no-real-time-wait:src/renderer/src/components/terminal-pane/layout/split/resolve-split-cwd.test.ts
|
||||
2 test-no-real-time-wait:src/renderer/src/components/terminal-pane/pty-connection/emulation/fish-color-scheme-child-stdin.node-pty.test.ts
|
||||
@@ -634,7 +633,7 @@
|
||||
2 test-no-wall-clock:src/renderer/src/components/dashboard/useLiveDashboardSnapshot.test.ts
|
||||
1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.opening-send.test.tsx
|
||||
1 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.queued-turn-order.test.tsx
|
||||
3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx
|
||||
2 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx
|
||||
3 test-no-wall-clock:src/renderer/src/components/native-chat/conversation/turns/NativeChatResolvedView.turn-status.test.tsx
|
||||
1 test-no-wall-clock:src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx
|
||||
3 test-no-wall-clock:src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx
|
||||
|
||||
@@ -307,6 +307,27 @@
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx",
|
||||
"kind": "object-property:label",
|
||||
"text": "Shift",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx",
|
||||
"kind": "object-property:label",
|
||||
"text": "Ctrl",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "mobile/src/terminal/session/MobileSessionLatchKeys.tsx",
|
||||
"kind": "object-property:label",
|
||||
"text": "Alt",
|
||||
"dynamic": false,
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"filePath": "mobile/src/tasks/mobile-smart-source-modes.ts",
|
||||
"kind": "object-property:label",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4589,7 +4589,6 @@
|
||||
"src/packages/process-host/src/run-process-windows-tree-kill.test.ts": 81,
|
||||
"src/packages/process-host/src/run-process.test.ts": 9406,
|
||||
"src/packages/process-host/src/spawn-observer.test.ts": 357,
|
||||
"src/packages/process-host/src/spawn-process-stdio.test.ts": 311,
|
||||
"src/packages/process-host/src/windows-command-line.test.ts": 73,
|
||||
"src/packages/process-host/src/windows-tree-kill.test.ts": 81,
|
||||
"src/packages/process-host/src/wsl-distro-allowlist.test.ts": 55,
|
||||
@@ -5173,7 +5172,6 @@
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatMessageList.test.tsx": 4252,
|
||||
"src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-indicator.test.tsx": 4070,
|
||||
"src/renderer/src/components/native-chat/conversation/slots/NativeChatMessageList.turn-membership.test.tsx": 3527,
|
||||
"src/renderer/src/components/native-chat/conversation/turns/NativeChatMessageList.turn-status.test.tsx": 3370,
|
||||
"src/renderer/src/components/native-chat/session/structured/delivery/NativeChatMessageList.unsent-message.test.tsx": 3069,
|
||||
"src/renderer/src/components/native-chat/viewport/scroll/NativeChatMessageList.visual-scroll.test.tsx": 6691,
|
||||
"src/renderer/src/components/native-chat/viewport/virtualization/NativeChatMessageList.windowing.test.tsx": 20958,
|
||||
@@ -5201,9 +5199,7 @@
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx": 2911,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.retained-draft.test.tsx": 3736,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459,
|
||||
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.wsl-host-stopped.test.tsx": 3657,
|
||||
"src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583,
|
||||
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolLine.test.tsx": 3544,
|
||||
"src/renderer/src/components/native-chat/tools/lines/NativeChatToolOutput.test.tsx": 410,
|
||||
@@ -5268,7 +5264,6 @@
|
||||
"src/renderer/src/components/native-chat/queue/editing/native-chat-queued-edit-draft.test.ts": 649,
|
||||
"src/renderer/src/components/native-chat/viewport/rail/native-chat-rail-outline-parity.test.ts": 497,
|
||||
"src/renderer/src/components/native-chat/viewport/scroll/native-chat-reader-scroll-input.test.tsx": 311,
|
||||
"src/renderer/src/components/native-chat/paste/native-chat-remote-image-paste.test.tsx": 1834,
|
||||
"src/renderer/src/components/native-chat/attachments/uploads/native-chat-resolved-path-ownership.test.ts": 1749,
|
||||
"src/renderer/src/components/native-chat/viewport/virtualization/native-chat-row-height-estimate.test.ts": 293,
|
||||
"src/renderer/src/components/native-chat/drafts/native-chat-sent-prompt-history.test.ts": 217,
|
||||
@@ -5278,7 +5273,6 @@
|
||||
"src/renderer/src/components/native-chat/pane/routing/native-chat-split-flow.test.ts": 1916,
|
||||
"src/renderer/src/components/native-chat/composer/submit/native-chat-structured-send-composition-clear.test.tsx": 2098,
|
||||
"src/renderer/src/components/native-chat/subagents/native-chat-subagent-handoff-copy-budget.test.ts": 362,
|
||||
"src/renderer/src/components/native-chat/subagents/native-chat-subagent-section-work-runs.test.ts": 278,
|
||||
"src/renderer/src/components/native-chat/pane/routing/native-chat-tab-directory.test.ts": 304,
|
||||
"src/renderer/src/components/native-chat/native-chat-task-list-state.test.ts": 62,
|
||||
"src/renderer/src/components/native-chat/native-chat-thread-goal-rows.test.ts": 50,
|
||||
@@ -5689,7 +5683,6 @@
|
||||
"src/renderer/src/components/sidebar/worktree-list/rows/repo-header-ssh-isolation.test.tsx": 2945,
|
||||
"src/renderer/src/components/sidebar/worktree-list/rows/section-header-create-host.test.tsx": 2393,
|
||||
"src/renderer/src/components/sidebar/worktree-list/viewport/hard-scroll-up.test.ts": 66,
|
||||
"src/renderer/src/components/sidebar/worktree-list/viewport/header-folder-composition.test.tsx": 3725,
|
||||
"src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.ts": 293,
|
||||
"src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.test.tsx": 269,
|
||||
"src/renderer/src/components/sidebar/worktree-list/drag/worktree-manual-order-store-write.test.ts": 2144,
|
||||
|
||||
@@ -13,20 +13,6 @@ const checks = [
|
||||
args: ['test', '--package-path', 'native/computer-use-macos'],
|
||||
enabled: process.platform === 'darwin'
|
||||
},
|
||||
{
|
||||
name: 'Linux provider Python syntax',
|
||||
command: 'python3',
|
||||
args: [
|
||||
'-c',
|
||||
[
|
||||
'import ast, pathlib',
|
||||
'source=pathlib.Path("native/computer-use-linux/runtime.py").read_text(encoding="utf-8")',
|
||||
'ast.parse(source)',
|
||||
'print("syntax-ok")'
|
||||
].join(';')
|
||||
],
|
||||
enabled: true
|
||||
},
|
||||
{
|
||||
name: 'Linux snapshot renderer tests',
|
||||
command: 'python3',
|
||||
|
||||
@@ -22,8 +22,7 @@ const contracts = [
|
||||
'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/claude-usage/scanner-incremental-append.test.ts',
|
||||
'src/main/claude-usage/store-checkpoint-persistence.test.ts',
|
||||
'src/renderer/src/components/native-chat/surfaces/integration/NativeChatResolvedView.streaming-input.test.tsx'
|
||||
'src/main/claude-usage/store-checkpoint-persistence.test.ts'
|
||||
]
|
||||
for (const contract of contracts) {
|
||||
if (!existsSync(resolve(contract))) {
|
||||
|
||||
@@ -27,4 +27,4 @@ The chat root (`.native-chat-appearance`) redefines these steps as ratios of the
|
||||
- **Focus rings:** full-width transcript rows use the inset ring (`focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring`) so it isn't clipped by the scroll container; standalone controls use `focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`. Inside the chat `--ring` is `--chat-focus-ring`, which clears 3:1 on the canvas; don't lower its opacity.
|
||||
- **Theme overrides:** plugin themes can set `--chat-bold-foreground`, `--chat-muted-foreground`, `--chat-inline-code`, `--chat-inline-code-foreground`, `--chat-code-block`, `--chat-selection` and `--chat-selection-foreground`. They feed `text-chat-foreground-faint`, `bg-chat-inline-code-surface`, `bg-chat-code-surface` and the chat root's `::selection`, so use those rather than reading the theme tokens directly.
|
||||
- **Selection** inside the chat is the link hue mixed into the canvas (close to the system highlight), with selected text in the full foreground so every role stays 4.5:1. Don't add per-component `selection:` colors in transcript text.
|
||||
- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row.
|
||||
- **State colours:** warnings use `text-chat-warning`; diff lines use `text-chat-diff-added` / `text-chat-diff-removed`; what the reader has not seen yet uses `text-chat-unread`. They are mixed toward the foreground so they pass text contrast in light and dark. Don't use raw palette colours (`text-yellow-500`) or the git decoration tokens for text on a tinted row.
|
||||
|
||||
@@ -5,15 +5,9 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
// Also tells TanStack observers on a microtask, so act() sees replies.
|
||||
import '../test-support/query-client-test-renderer'
|
||||
import { settleQueryNotifications } from '../test-support/rpc-recording/hook-mount'
|
||||
import type { OrcaQueryStoreBackend } from '../device-store/query-storage'
|
||||
import { createOrcaQueryClient } from '../query/orca-query-client'
|
||||
import { createHostQueryPersistence, persistedHostQueryKey } from '../query/host-query-persistence'
|
||||
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
|
||||
import {
|
||||
accountsSnapshotFamily,
|
||||
accountsSnapshotKey,
|
||||
accountsSnapshotOptions
|
||||
} from './accounts-snapshot-stream'
|
||||
import { accountsSnapshotKey } from './accounts-snapshot-stream'
|
||||
import { useMobileAccountsSnapshot } from './use-mobile-accounts-snapshot'
|
||||
|
||||
const HOST = 'host-1'
|
||||
@@ -89,24 +83,6 @@ async function mountAccounts(queryClient: QueryClient, client: RpcClient) {
|
||||
}
|
||||
}
|
||||
|
||||
function memoryStore(): OrcaQueryStoreBackend {
|
||||
const rows = new Map<string, string>()
|
||||
return {
|
||||
hostId: HOST,
|
||||
read: async (keys) => ({ status: 'ok', values: keys.map((key) => rows.get(key) ?? null) }),
|
||||
write: async (ops) => {
|
||||
for (const op of ops) {
|
||||
if (op.value === null) {
|
||||
rows.delete(op.key)
|
||||
} else {
|
||||
rows.set(op.key, op.value)
|
||||
}
|
||||
}
|
||||
return { written: true }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('accounts snapshot', () => {
|
||||
it('still shows usage when the stream fails and accounts.list answers', async () => {
|
||||
const port = accountsClient(SNAPSHOT)
|
||||
@@ -128,24 +104,4 @@ describe('accounts snapshot', () => {
|
||||
'claude@example.test'
|
||||
])
|
||||
})
|
||||
|
||||
it('never counts a stored snapshot as live, even one written after the connect', async () => {
|
||||
const store = memoryStore()
|
||||
// Native Home's own stream stores the snapshot after the connect the page then reads.
|
||||
const home = createOrcaQueryClient()
|
||||
const homePersistence = createHostQueryPersistence(home, store)
|
||||
home.getQueryCache().build(home, accountsSnapshotOptions(HOST))
|
||||
home.setQueryData(accountsSnapshotKey(HOST), SNAPSHOT, { updatedAt: CONNECTED_AT + 1 })
|
||||
await settleQueryNotifications()
|
||||
await homePersistence.flush()
|
||||
home.clear()
|
||||
|
||||
const page = createOrcaQueryClient()
|
||||
await createHostQueryPersistence(page, store).restore([
|
||||
persistedHostQueryKey(accountsSnapshotFamily, accountsSnapshotKey(HOST))!
|
||||
])
|
||||
const read = await mountAccounts(page, accountsClient(SNAPSHOT).client)
|
||||
expect(read().snapshot?.claude.accounts.map((account) => account.id)).toEqual(['claude-1'])
|
||||
expect(read().live).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -41,6 +41,9 @@ export const customKeyModalStyles = themedStyleSheet(() => ({
|
||||
borderRadius: radii.surface,
|
||||
overflow: 'hidden'
|
||||
},
|
||||
smartRailGroup: {
|
||||
marginTop: spacing.md
|
||||
},
|
||||
shortcutForm: {
|
||||
paddingTop: spacing.sm
|
||||
},
|
||||
|
||||
@@ -19,6 +19,7 @@ import { useMobileTranslation } from '../i18n/use-mobile-translation'
|
||||
import { MobileSwitch } from './MobileSwitch'
|
||||
import { ListGroup, ListRow } from './list/ListGroup'
|
||||
import { FieldTextInput } from './composer-input/FieldTextInput'
|
||||
import { SmartRailRow } from './SmartRailRow'
|
||||
|
||||
type Step = 'choose-type' | 'shortcut-combo' | 'special-keys' | 'text-macro'
|
||||
|
||||
@@ -62,9 +63,11 @@ type Props = {
|
||||
onClose: () => void
|
||||
onKeysChanged: (keys: CustomKey[]) => void
|
||||
onManageShortcuts?: () => void
|
||||
smartRail?: { enabled: boolean; onChange: (enabled: boolean) => void }
|
||||
}
|
||||
|
||||
export function CustomKeyModal({ visible, onClose, onKeysChanged, onManageShortcuts }: Props) {
|
||||
export function CustomKeyModal(props: Props) {
|
||||
const { visible, onClose, onKeysChanged, onManageShortcuts, smartRail } = props
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const [step, setStep] = useState<Step>('choose-type')
|
||||
@@ -235,6 +238,11 @@ export function CustomKeyModal({ visible, onClose, onKeysChanged, onManageShortc
|
||||
) : null}
|
||||
</ListGroup>
|
||||
)}
|
||||
{step === 'choose-type' && smartRail ? (
|
||||
<ListGroup style={styles.smartRailGroup}>
|
||||
<SmartRailRow {...smartRail} />
|
||||
</ListGroup>
|
||||
) : null}
|
||||
|
||||
{step === 'shortcut-combo' && (
|
||||
<View style={styles.shortcutForm}>
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { ListRow } from './list/ListGroup'
|
||||
import { MobileSwitch } from './MobileSwitch'
|
||||
import { useMobileTranslation } from '../i18n/use-mobile-translation'
|
||||
|
||||
/** The Smart rail setting: keys for what the terminal's agent is doing, at the front of the key row. */
|
||||
export function SmartRailRow({
|
||||
enabled,
|
||||
onChange
|
||||
}: {
|
||||
enabled: boolean
|
||||
onChange: (enabled: boolean) => void
|
||||
}): React.JSX.Element {
|
||||
const t = useMobileTranslation()
|
||||
const title = t('components.smartRailRow.title', 'Smart rail')
|
||||
return (
|
||||
<ListRow
|
||||
title={title}
|
||||
subtitle={t('components.smartRailRow.subtitle', 'Shows keys for what your agent is doing')}
|
||||
accessory={
|
||||
<MobileSwitch accessibilityLabel={title} value={enabled} onValueChange={onChange} />
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
setTerminalAccessoryBuiltInVisible
|
||||
} from '../terminal/terminal-accessory-layout'
|
||||
import { MobileSwitch } from './MobileSwitch'
|
||||
import { SmartRailRow } from './SmartRailRow'
|
||||
|
||||
// Absolutely positioned DragReorderList rows require one fixed height per section.
|
||||
const REORDER_ROW_HEIGHT = 56
|
||||
@@ -148,10 +149,13 @@ export function TerminalShortcutSettings({
|
||||
[persistLayout]
|
||||
)
|
||||
|
||||
// Resetting the keys leaves the Smart rail setting alone.
|
||||
const resetBuiltInKeys = useCallback(() => {
|
||||
const next = defaultLayout()
|
||||
setShortcutLayout(next)
|
||||
persistLayout(next)
|
||||
setShortcutLayout((current) => {
|
||||
const next = { ...defaultLayout(), smartRail: current.smartRail }
|
||||
persistLayout(next)
|
||||
return next
|
||||
})
|
||||
}, [defaultLayout, persistLayout])
|
||||
|
||||
const reorderCustomKeys = useCallback(
|
||||
@@ -182,6 +186,18 @@ export function TerminalShortcutSettings({
|
||||
|
||||
return (
|
||||
<>
|
||||
<SettingsSection>
|
||||
<SmartRailRow
|
||||
enabled={shortcutLayout.smartRail === true}
|
||||
onChange={(enabled) =>
|
||||
setShortcutLayout((current) => {
|
||||
const next = { ...current, smartRail: enabled }
|
||||
persistLayout(next)
|
||||
return next
|
||||
})
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
{hasPad ? (
|
||||
<SettingsSection
|
||||
title={t('components.terminalShortcutSettings.directionPad', 'DIRECTION PAD')}
|
||||
|
||||
@@ -315,7 +315,11 @@
|
||||
"forkOriginalMissingNamed": "{{agent}} could not find this response in \"{{detail}}\". Open that chat and fork from there.",
|
||||
"forkOriginalUnavailable": "{{agent}} cannot fork this response in the original chat. Open it and fork from there.",
|
||||
"forkOriginalUnavailableNamed": "{{agent}} cannot fork this response in \"{{detail}}\". Open that chat and fork from there.",
|
||||
"pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal."
|
||||
"pluginInputRequired": "{{agent}} stopped because the \"{{plugin}}\" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal.",
|
||||
"providerResponseFailed": "{{agent}} couldn't finish this response. Open Details for more information.",
|
||||
"providerSafetyStopped": "{{agent}} stopped this response after a safety check. Review your request and send again.",
|
||||
"providerUnavailable": "{{agent}} couldn't respond because the service is busy. Pick another model, or wait a little and send again.",
|
||||
"selectedModel": "the selected model"
|
||||
},
|
||||
"fileReader": {
|
||||
"reviewNotes_one": "{{count}} review note",
|
||||
|
||||
@@ -2153,6 +2153,10 @@
|
||||
"providerExitedRejection": "{{agent}} wurde gestoppt, bevor diese Nachricht gesendet wurde.",
|
||||
"providerExitedRow": "{{agent}} wurde während dieser Antwort gestoppt. Die Unterhaltung kann fortgesetzt werden.",
|
||||
"providerRateLimited": "{{agent}} hat das Ratenlimit erreicht und versucht es erneut.",
|
||||
"providerUnavailable": "{{agent}} konnte nicht antworten, weil der Dienst ausgelastet ist. Wähle ein anderes Modell oder warte kurz und sende erneut.",
|
||||
"providerSafetyStopped": "{{agent}} hat diese Antwort nach einer Sicherheitsprüfung gestoppt. Überprüfe deine Anfrage und sende sie erneut.",
|
||||
"providerResponseFailed": "{{agent}} konnte diese Antwort nicht abschließen. Öffnen Sie die Details für weitere Informationen.",
|
||||
"selectedModel": "das ausgewählte Modell",
|
||||
"providerRejected": "{{agent}} hat diese Nachricht nicht angenommen.",
|
||||
"providerRejectedQuoted": "{{agent}} hat diese Nachricht nicht angenommen: {{detail}}.",
|
||||
"providerRetryLastError": "Letzter Fehler: {{detail}}.",
|
||||
|
||||
@@ -1479,6 +1479,10 @@
|
||||
},
|
||||
"offlineAsOfTime": {
|
||||
"yesterday": "yesterday, {{time}}"
|
||||
},
|
||||
"smartRailRow": {
|
||||
"title": "Smart rail",
|
||||
"subtitle": "Shows keys for what your agent is doing"
|
||||
}
|
||||
},
|
||||
"pullRequest": {
|
||||
@@ -2638,6 +2642,10 @@
|
||||
"modelUnavailable": "{{agent}} couldn't use {{detail}}. Pick another model and send again.",
|
||||
"modelUnavailableUpdate": "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.",
|
||||
"modelNotSelected": "{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.",
|
||||
"providerUnavailable": "{{agent}} couldn't respond because the service is busy. Pick another model, or wait a little and send again.",
|
||||
"providerSafetyStopped": "{{agent}} stopped this response after a safety check. Review your request and send again.",
|
||||
"providerResponseFailed": "{{agent}} couldn't finish this response. Open Details for more information.",
|
||||
"selectedModel": "the selected model",
|
||||
"providerRejected": "{{agent}} didn't accept this message.",
|
||||
"providerRejectedQuoted": "{{agent}} didn't accept this message: {{detail}}.",
|
||||
"attachmentEmpty": "An image on this message is empty, so the message was not sent.",
|
||||
@@ -2883,6 +2891,25 @@
|
||||
},
|
||||
"usePrTextAction": {
|
||||
"updateFailed": "Failed to update pull request."
|
||||
},
|
||||
"smartKeys": {
|
||||
"always": "Always",
|
||||
"answer": "Answer",
|
||||
"background": "Background",
|
||||
"cancel": "Cancel",
|
||||
"confirm": "Confirm",
|
||||
"edit": "Edit",
|
||||
"history": "History",
|
||||
"keyLabel": "{{word}}, sends {{combo}}",
|
||||
"mode": "Mode",
|
||||
"no": "No",
|
||||
"queue": "Queue",
|
||||
"reject": "Reject",
|
||||
"rewind": "Rewind",
|
||||
"sendNow": "Send now",
|
||||
"skip": "Skip",
|
||||
"stop": "Stop",
|
||||
"yes": "Yes"
|
||||
}
|
||||
},
|
||||
"chat": {
|
||||
|
||||
@@ -2221,6 +2221,10 @@
|
||||
"providerExitedRejection": "{{agent}} se detuvo antes de que se enviara este mensaje.",
|
||||
"providerExitedRow": "{{agent}} se detuvo mientras esta respuesta estaba en curso. Puede continuar en esta conversación.",
|
||||
"providerRateLimited": "{{agent}} alcanzó un límite de solicitudes y está reintentando.",
|
||||
"providerUnavailable": "{{agent}} no pudo responder porque el servicio está ocupado. Elige otro modelo o espera un poco y vuelve a enviar el mensaje.",
|
||||
"providerSafetyStopped": "{{agent}} detuvo esta respuesta tras una comprobación de seguridad. Revisa tu solicitud y vuelve a enviarla.",
|
||||
"providerResponseFailed": "{{agent}} no pudo terminar esta respuesta. Abre los detalles para obtener más información.",
|
||||
"selectedModel": "el modelo seleccionado",
|
||||
"providerRejected": "{{agent}} no aceptó este mensaje.",
|
||||
"providerRejectedQuoted": "{{agent}} no aceptó este mensaje: {{detail}}.",
|
||||
"providerRetryLastError": "Último error: {{detail}}.",
|
||||
|
||||
@@ -2222,6 +2222,10 @@
|
||||
"providerExitedRejection": "{{agent}} s'est arrêté avant l'envoi de ce message.",
|
||||
"providerExitedRow": "{{agent}} s'est arrêté pendant que cette réponse était en cours. Vous pouvez continuer dans cette conversation.",
|
||||
"providerRateLimited": "{{agent}} est limité en débit et réessaie.",
|
||||
"providerUnavailable": "{{agent}} n’a pas pu répondre car le service est occupé. Choisissez un autre modèle ou patientez un peu, puis renvoyez le message.",
|
||||
"providerSafetyStopped": "{{agent}} a arrêté cette réponse après un contrôle de sécurité. Vérifiez votre demande et renvoyez-la.",
|
||||
"providerResponseFailed": "{{agent}} n’a pas pu terminer cette réponse. Ouvrez les détails pour en savoir plus.",
|
||||
"selectedModel": "le modèle sélectionné",
|
||||
"providerRejected": "{{agent}} n'a pas accepté ce message.",
|
||||
"providerRejectedQuoted": "{{agent}} n'a pas accepté ce message : {{detail}}.",
|
||||
"providerRetryLastError": "Dernière erreur : {{detail}}.",
|
||||
|
||||
@@ -2149,6 +2149,10 @@
|
||||
"providerExitedRejection": "このメッセージが送信される前に {{agent}} が停止しました。",
|
||||
"providerExitedRow": "この応答の途中で {{agent}} が停止しました。この会話で続けることができます。",
|
||||
"providerRateLimited": "{{agent}} はレート制限を受けているため、再試行しています。",
|
||||
"providerUnavailable": "サービスが混雑しているため、{{agent}} は応答できませんでした。別のモデルを選ぶか、しばらく待ってから再送してください。",
|
||||
"providerSafetyStopped": "{{agent}} は安全確認の後、この応答を停止しました。リクエストを見直して再送してください。",
|
||||
"providerResponseFailed": "{{agent}} はこの応答を完了できませんでした。詳細を開いて確認してください。",
|
||||
"selectedModel": "選択されたモデル",
|
||||
"providerRejected": "{{agent}} はこのメッセージを受け付けませんでした。",
|
||||
"providerRejectedQuoted": "{{agent}} はこのメッセージを受け付けませんでした: {{detail}}。",
|
||||
"providerRetryLastError": "直近のエラー: {{detail}}。",
|
||||
|
||||
@@ -2149,6 +2149,10 @@
|
||||
"providerExitedRejection": "이 메시지가 전송되기 전에 {{agent}}이(가) 중지되었습니다.",
|
||||
"providerExitedRow": "이 응답이 진행되는 동안 {{agent}}이(가) 중지되었습니다. 이 대화에서 계속할 수 있습니다.",
|
||||
"providerRateLimited": "{{agent}}이(가) 속도 제한에 걸려 다시 시도하고 있습니다.",
|
||||
"providerUnavailable": "서비스가 혼잡하여 {{agent}}이(가) 응답하지 못했습니다. 다른 모델을 선택하거나 잠시 기다린 후 다시 보내세요.",
|
||||
"providerSafetyStopped": "{{agent}}이(가) 안전 검사 후 이 응답을 중단했습니다. 요청을 검토한 후 다시 보내세요.",
|
||||
"providerResponseFailed": "{{agent}}이(가) 이 응답을 완료하지 못했습니다. 자세한 내용을 열어 확인하세요.",
|
||||
"selectedModel": "선택한 모델",
|
||||
"providerRejected": "{{agent}}이(가) 이 메시지를 받아들이지 않았습니다.",
|
||||
"providerRejectedQuoted": "{{agent}}이(가) 이 메시지를 받아들이지 않았습니다: {{detail}}.",
|
||||
"providerRetryLastError": "마지막 오류: {{detail}}.",
|
||||
|
||||
@@ -2221,6 +2221,10 @@
|
||||
"providerExitedRejection": "{{agent}} parou antes de esta mensagem ser enviada.",
|
||||
"providerExitedRow": "{{agent}} parou enquanto esta resposta estava em andamento. Você pode continuar nesta conversa.",
|
||||
"providerRateLimited": "{{agent}} atingiu o limite de requisições e está tentando novamente.",
|
||||
"providerUnavailable": "{{agent}} não conseguiu responder porque o serviço está ocupado. Escolha outro modelo ou aguarde um pouco e envie novamente.",
|
||||
"providerSafetyStopped": "{{agent}} interrompeu esta resposta após uma verificação de segurança. Revise sua solicitação e envie novamente.",
|
||||
"providerResponseFailed": "{{agent}} não conseguiu concluir esta resposta. Abra os detalhes para obter mais informações.",
|
||||
"selectedModel": "o modelo selecionado",
|
||||
"providerRejected": "{{agent}} não aceitou esta mensagem.",
|
||||
"providerRejectedQuoted": "{{agent}} não aceitou esta mensagem: {{detail}}.",
|
||||
"providerRetryLastError": "Último erro: {{detail}}.",
|
||||
|
||||
@@ -2289,6 +2289,10 @@
|
||||
"providerExitedRejection": "{{agent}} остановился до отправки этого сообщения.",
|
||||
"providerExitedRow": "{{agent}} остановился во время ответа. Вы можете продолжить этот разговор.",
|
||||
"providerRateLimited": "{{agent}} повторяет попытку из-за ограничения частоты запросов.",
|
||||
"providerUnavailable": "{{agent}} не смог ответить, поскольку сервис занят. Выберите другую модель или немного подождите и отправьте сообщение снова.",
|
||||
"providerSafetyStopped": "{{agent}} остановил этот ответ после проверки безопасности. Проверьте запрос и отправьте его снова.",
|
||||
"providerResponseFailed": "{{agent}} не удалось завершить этот ответ. Откройте подробности, чтобы узнать больше.",
|
||||
"selectedModel": "выбранную модель",
|
||||
"providerRejected": "{{agent}} не принял это сообщение.",
|
||||
"providerRejectedQuoted": "{{agent}} не принял это сообщение: {{detail}}.",
|
||||
"providerRetryLastError": "Последняя ошибка: {{detail}}.",
|
||||
|
||||
@@ -2153,6 +2153,10 @@
|
||||
"providerExitedRejection": "Bu mesaj gönderilmeden önce {{agent}} durdu.",
|
||||
"providerExitedRow": "Bu yanıt hazırlanırken {{agent}} durdu. Bu konuşmada devam edebilirsiniz.",
|
||||
"providerRateLimited": "{{agent}} istek hızı sınırına ulaştı ve yeniden deniyor.",
|
||||
"providerUnavailable": "Hizmet meşgul olduğu için {{agent}} yanıt veremedi. Başka bir model seçin veya biraz bekleyip yeniden gönderin.",
|
||||
"providerSafetyStopped": "{{agent}}, bir güvenlik kontrolünden sonra bu yanıtı durdurdu. İsteğinizi gözden geçirip yeniden gönderin.",
|
||||
"providerResponseFailed": "{{agent}} bu yanıtı tamamlayamadı. Daha fazla bilgi için ayrıntıları açın.",
|
||||
"selectedModel": "seçilen modeli",
|
||||
"providerRejected": "{{agent}} bu mesajı kabul etmedi.",
|
||||
"providerRejectedQuoted": "{{agent}} bu mesajı kabul etmedi: {{detail}}.",
|
||||
"providerRetryLastError": "Son hata: {{detail}}.",
|
||||
|
||||
@@ -2149,6 +2149,10 @@
|
||||
"providerExitedRejection": "{{agent}} 在傳送此訊息前已停止。",
|
||||
"providerExitedRow": "{{agent}} 在產生此回覆時停止了。您可以在此對話中繼續。",
|
||||
"providerRateLimited": "{{agent}} 受到速率限制,正在重試。",
|
||||
"providerUnavailable": "{{agent}} 因服務忙碌而無法回覆。請選擇其他模型,或稍候片刻後重新傳送。",
|
||||
"providerSafetyStopped": "{{agent}} 在安全檢查後停止了此次回覆。請檢查您的請求後重新傳送。",
|
||||
"providerResponseFailed": "{{agent}} 未能完成此回覆。開啟詳細資料以取得更多資訊。",
|
||||
"selectedModel": "所選模型",
|
||||
"providerRejected": "{{agent}} 未接受此訊息。",
|
||||
"providerRejectedQuoted": "{{agent}} 未接受此訊息:{{detail}}。",
|
||||
"providerRetryLastError": "上次錯誤:{{detail}}。",
|
||||
|
||||
@@ -2149,6 +2149,10 @@
|
||||
"providerExitedRejection": "{{agent}} 在发送此消息前已停止。",
|
||||
"providerExitedRow": "{{agent}} 在生成此回复时停止了。您可以在此对话中继续。",
|
||||
"providerRateLimited": "{{agent}} 已被限流,正在重试。",
|
||||
"providerUnavailable": "{{agent}} 因服务繁忙而无法回复。请选择其他模型,或稍等片刻后重新发送。",
|
||||
"providerSafetyStopped": "{{agent}} 在安全检查后停止了此次回复。请检查您的请求后重新发送。",
|
||||
"providerResponseFailed": "{{agent}} 未能完成此回复。打开详情了解更多信息。",
|
||||
"selectedModel": "所选模型",
|
||||
"providerRejected": "{{agent}} 未接受此消息。",
|
||||
"providerRejectedQuoted": "{{agent}} 未接受此消息:{{detail}}。",
|
||||
"providerRetryLastError": "上次错误:{{detail}}。",
|
||||
|
||||
@@ -60,7 +60,6 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes
|
||||
<View style={dockStyles.inputBar}>
|
||||
<LiveInputField
|
||||
controller={controller}
|
||||
keysInRail={rail.keysInRail}
|
||||
trailing={
|
||||
<MobileTerminalLiveInputStatus
|
||||
dictation={dictation}
|
||||
@@ -95,11 +94,9 @@ export function MobileSessionCommandDock({ controller }: { controller: MobileSes
|
||||
// Only this field reads the typed text, so a keystroke re-renders it and not the dock or session.
|
||||
function LiveInputField({
|
||||
controller,
|
||||
keysInRail,
|
||||
trailing
|
||||
}: {
|
||||
controller: MobileSessionController
|
||||
keysInRail: boolean
|
||||
trailing: ReactNode
|
||||
}) {
|
||||
const t = useMobileTranslation()
|
||||
@@ -124,11 +121,8 @@ function LiveInputField({
|
||||
trailing={trailing}
|
||||
value={text}
|
||||
onChange={(event) => {
|
||||
// A ctrl/alt/shift held on the Duo rail turns the next typed letter into a combo, while the rail shows it.
|
||||
if (
|
||||
!keysInRail ||
|
||||
!dockKeys.interceptTypedCharacter(text, event.nativeEvent.text, liveInputRef)
|
||||
) {
|
||||
// A held Shift, Ctrl or Alt on the key row or the Duo rail turns the next typed letter into a combo.
|
||||
if (!dockKeys.interceptTypedCharacter(text, event.nativeEvent.text, liveInputRef)) {
|
||||
handleLiveInputChange(event)
|
||||
}
|
||||
}}
|
||||
|
||||
@@ -77,6 +77,8 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC
|
||||
confirmDiscardMarkdown,
|
||||
handleDeleteCustomKey,
|
||||
handleManageShortcuts,
|
||||
smartRailEnabled,
|
||||
handleSmartRailChange,
|
||||
handleClearTerminal,
|
||||
handleCreateTerminal,
|
||||
launchQuickCommand,
|
||||
@@ -363,6 +365,7 @@ export function MobileSessionSheets({ controller }: { controller: MobileSessionC
|
||||
onClose={() => setShowCustomKeyModal(false)}
|
||||
onKeysChanged={setCustomKeys}
|
||||
onManageShortcuts={handleManageShortcuts}
|
||||
smartRail={{ enabled: smartRailEnabled, onChange: handleSmartRailChange }}
|
||||
/>
|
||||
<MobileDictationSetupSheet
|
||||
visible={showDictationSetup}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { AGENT_SESSION_FAILURE_COPY } from '../../../src/shared/agent-session/failures/agent-session-failure-copy'
|
||||
import type {
|
||||
AgentSessionFailureCopyId,
|
||||
AgentSessionFailureCopyValues
|
||||
@@ -53,6 +54,26 @@ export const SEND_FAILURE_COPY = {
|
||||
"{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.",
|
||||
values
|
||||
),
|
||||
selectedModel: (values) =>
|
||||
translate('session.failure.selectedModel', AGENT_SESSION_FAILURE_COPY.selectedModel, values),
|
||||
providerUnavailable: (values) =>
|
||||
translate(
|
||||
'session.failure.providerUnavailable',
|
||||
AGENT_SESSION_FAILURE_COPY.providerUnavailable,
|
||||
values
|
||||
),
|
||||
providerSafetyStopped: (values) =>
|
||||
translate(
|
||||
'session.failure.providerSafetyStopped',
|
||||
AGENT_SESSION_FAILURE_COPY.providerSafetyStopped,
|
||||
values
|
||||
),
|
||||
providerResponseFailed: (values) =>
|
||||
translate(
|
||||
'session.failure.providerResponseFailed',
|
||||
AGENT_SESSION_FAILURE_COPY.providerResponseFailed,
|
||||
values
|
||||
),
|
||||
providerRejected: (values) =>
|
||||
translate('session.failure.providerRejected', "{{agent}} didn't accept this message.", values),
|
||||
providerRejectedQuoted: (values) =>
|
||||
|
||||
@@ -57,3 +57,31 @@ it('settles a proven missing-original fork refusal but keeps a lost earlier atte
|
||||
(await createMobileStructuredAgentSession(lost, 'workspace-1', 'opencode', forkFrom)).kind
|
||||
).toBe('unknown')
|
||||
})
|
||||
|
||||
it('settles a proven fork read refusal without settling a prior lost copy', async () => {
|
||||
const refusal = {
|
||||
ok: true,
|
||||
result: {
|
||||
ok: false,
|
||||
refusal: {
|
||||
code: 'agent_session_identity_required',
|
||||
details: { reason: 'transcriptUnreadable' },
|
||||
createAttemptRefusedBeforeCommit: true,
|
||||
message: 'Codex could not read the saved chat.'
|
||||
}
|
||||
}
|
||||
}
|
||||
const client = clientReturning({ ok: true, result: { supported: true } }, refusal)
|
||||
const forkFrom = { sessionId: 'source-chat', throughItemId: 'codex:source:selected:1' }
|
||||
expect(
|
||||
(await createMobileStructuredAgentSession(client, 'workspace-1', 'codex', forkFrom)).kind
|
||||
).toBe('failed')
|
||||
const lost = clientReturning({ ok: true, result: { supported: true } }, refusal)
|
||||
lost.sendRequest
|
||||
.mockImplementationOnce(async () => ({ ok: true, result: { supported: true } }))
|
||||
.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('copy reply lost')))
|
||||
.mockResolvedValueOnce(refusal)
|
||||
expect(
|
||||
(await createMobileStructuredAgentSession(lost, 'workspace-1', 'codex', forkFrom)).kind
|
||||
).toBe('unknown')
|
||||
})
|
||||
|
||||
@@ -7,7 +7,8 @@ import type {
|
||||
} from '../../../src/shared/agent-session/agent-session-wire'
|
||||
import {
|
||||
isDefinitiveAgentSessionCreateRefusal,
|
||||
isAgentSessionForkSourceAdmissionRefusal
|
||||
isAgentSessionForkSourceAdmissionRefusal,
|
||||
isAgentSessionCreateAdmissionRefusal
|
||||
} from '../../../src/shared/agent-session/failures/agent-session-definitive-refusal'
|
||||
import {
|
||||
createStructuredAgentSessionId,
|
||||
@@ -187,7 +188,8 @@ export async function createMobileStructuredAgentSession(
|
||||
forkFrom &&
|
||||
!priorCreateOutcomeUnknown &&
|
||||
result.refusal.createAttemptRefusedBeforeCommit === true &&
|
||||
isAgentSessionForkSourceAdmissionRefusal(result.refusal)
|
||||
(isAgentSessionForkSourceAdmissionRefusal(result.refusal) ||
|
||||
isAgentSessionCreateAdmissionRefusal(result.refusal))
|
||||
) {
|
||||
return {
|
||||
kind: 'failed',
|
||||
|
||||
@@ -12,6 +12,7 @@ import type { AgentJournalFreeTextInput } from '../../../../../src/shared/agent-
|
||||
import {
|
||||
askAcceptsEmptyAnswer,
|
||||
askConfirmAction,
|
||||
askQuestionShowsPreviews,
|
||||
askConfirmLabel,
|
||||
askTypedText,
|
||||
toggleAskOption
|
||||
@@ -65,7 +66,8 @@ export function MobileNativeChatAsk({
|
||||
}: Props): React.JSX.Element {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const { scrollRef, inputRef, revealReply, onViewportLayout } = useMobileNativeChatReplyScroll()
|
||||
const { scrollRef, inputRef, revealReply, scrollViewProps, revealContent } =
|
||||
useMobileNativeChatReplyScroll()
|
||||
const [index, setIndex] = useState(0)
|
||||
const [selections, setSelections] = useState<number[][]>(() => prompt.questions.map(() => []))
|
||||
const [otherText, setOtherText] = useState<string[]>(() =>
|
||||
@@ -109,11 +111,15 @@ export function MobileNativeChatAsk({
|
||||
return
|
||||
}
|
||||
const cur = selections[qi] ?? []
|
||||
// A pick reveals its preview, so a re-tap keeps it and the user confirms.
|
||||
const keep = optIndex !== OTHER && askQuestionShowsPreviews(prompt.questions[qi])
|
||||
const picked = !cur.includes(optIndex)
|
||||
const next = selections.map((s, i) => (i === qi ? toggleAskOption(cur, optIndex, multi) : s))
|
||||
const next = selections.map((s, i) =>
|
||||
i === qi ? toggleAskOption(cur, optIndex, multi, keep) : s
|
||||
)
|
||||
setSelections(next)
|
||||
autoAdvance.cancel()
|
||||
if (picked && !multi && optIndex !== OTHER) {
|
||||
if (picked && !multi && optIndex !== OTHER && !keep) {
|
||||
autoAdvance.schedule(() => void advance(next))
|
||||
}
|
||||
}
|
||||
@@ -246,12 +252,7 @@ export function MobileNativeChatAsk({
|
||||
</ScrollView>
|
||||
) : null}
|
||||
|
||||
<ScrollView
|
||||
ref={scrollRef}
|
||||
onLayout={onViewportLayout}
|
||||
style={styles.scroll}
|
||||
keyboardShouldPersistTaps="always"
|
||||
>
|
||||
<ScrollView {...scrollViewProps} style={styles.scroll} keyboardShouldPersistTaps="always">
|
||||
<View style={styles.questionRow}>
|
||||
<MobileNativeChatQuestionText title content={q.question} style={styles.questionText} />
|
||||
<MobileNativeChatCardHeaderAction
|
||||
@@ -270,6 +271,8 @@ export function MobileNativeChatAsk({
|
||||
key={`${optIndex}:${opt.label}`}
|
||||
label={opt.label}
|
||||
description={opt.description}
|
||||
preview={opt.preview}
|
||||
onPreviewLayout={revealContent}
|
||||
selected={(selections[index] ?? []).includes(optIndex)}
|
||||
multi={q.multiSelect}
|
||||
disabled={submitting}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import { Pressable, ScrollView, Text, View, type LayoutChangeEvent } from 'react-native'
|
||||
import { Check } from 'lucide-react-native'
|
||||
import {
|
||||
colors,
|
||||
@@ -14,6 +14,8 @@ import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
|
||||
export function MobileNativeChatAskOptionRow({
|
||||
label,
|
||||
description,
|
||||
preview,
|
||||
onPreviewLayout,
|
||||
selected,
|
||||
multi,
|
||||
disabled,
|
||||
@@ -21,13 +23,17 @@ export function MobileNativeChatAskOptionRow({
|
||||
}: {
|
||||
label: string
|
||||
description?: string
|
||||
/** Shown under the row while it is selected, as the agent wrote it. */
|
||||
preview?: string
|
||||
/** The preview's edges in the card's scroll content; the row renders as its direct children. */
|
||||
onPreviewLayout?: (top: number, bottom: number) => void
|
||||
selected: boolean
|
||||
multi?: boolean
|
||||
disabled: boolean
|
||||
onPress: () => void
|
||||
}): React.JSX.Element {
|
||||
useMobileColorScheme()
|
||||
return (
|
||||
const row = (
|
||||
<Pressable
|
||||
accessibilityRole={multi ? 'checkbox' : 'radio'}
|
||||
accessibilityState={{ checked: selected, disabled }}
|
||||
@@ -59,6 +65,30 @@ export function MobileNativeChatAskOptionRow({
|
||||
</View>
|
||||
</Pressable>
|
||||
)
|
||||
// One root shape whether or not the preview shows, so selecting never remounts the row.
|
||||
return (
|
||||
<>
|
||||
{row}
|
||||
{preview && selected ? (
|
||||
<View
|
||||
style={styles.preview}
|
||||
onLayout={(event: LayoutChangeEvent) => {
|
||||
const { y, height } = event.nativeEvent.layout
|
||||
onPreviewLayout?.(y, y + height)
|
||||
}}
|
||||
>
|
||||
<ScrollView nestedScrollEnabled showsVerticalScrollIndicator>
|
||||
{/* Mockups are drawn in columns, so they scroll sideways instead of wrapping at phone width. */}
|
||||
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
|
||||
<Text selectable style={styles.previewText}>
|
||||
{preview}
|
||||
</Text>
|
||||
</ScrollView>
|
||||
</ScrollView>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = themedStyleSheet(() => ({
|
||||
@@ -106,5 +136,19 @@ const styles = themedStyleSheet(() => ({
|
||||
optionDescription: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: typography.metaSize
|
||||
},
|
||||
preview: {
|
||||
backgroundColor: colors.bgPanel,
|
||||
borderWidth: 1,
|
||||
borderColor: colors.borderSubtle,
|
||||
borderRadius: concentricRadius(radii.surface, spacing.xs),
|
||||
padding: spacing.sm,
|
||||
marginBottom: spacing.xs,
|
||||
maxHeight: 220
|
||||
},
|
||||
previewText: {
|
||||
color: colors.textPrimary,
|
||||
fontFamily: typography.monoFamily,
|
||||
fontSize: typography.metaSize
|
||||
}
|
||||
}))
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
import { useRef } from 'react'
|
||||
import type { LayoutChangeEvent, ScrollView, TextInput } from 'react-native'
|
||||
import type {
|
||||
LayoutChangeEvent,
|
||||
NativeScrollEvent,
|
||||
NativeSyntheticEvent,
|
||||
ScrollView,
|
||||
TextInput
|
||||
} from 'react-native'
|
||||
|
||||
// Keep a focused reply in view when its card shrinks above the keyboard.
|
||||
export function useMobileNativeChatReplyScroll() {
|
||||
const scrollRef = useRef<ScrollView>(null)
|
||||
const inputRef = useRef<TextInput>(null)
|
||||
const viewportHeight = useRef(0)
|
||||
const scrollOffset = useRef(0)
|
||||
const revealReply = (): void => {
|
||||
if (inputRef.current?.isFocused()) {
|
||||
scrollRef.current?.scrollToEnd({ animated: false })
|
||||
@@ -20,5 +27,31 @@ export function useMobileNativeChatReplyScroll() {
|
||||
revealReply()
|
||||
}
|
||||
}
|
||||
return { scrollRef, inputRef, revealReply, onViewportLayout }
|
||||
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>): void => {
|
||||
scrollOffset.current = event.nativeEvent.contentOffset.y
|
||||
}
|
||||
// Scroll just enough to show content that opened below the visible edge, never past its top.
|
||||
const revealContent = (top: number, bottom: number): void => {
|
||||
const hidden = bottom - (scrollOffset.current + viewportHeight.current)
|
||||
if (viewportHeight.current > 0 && hidden > 0) {
|
||||
scrollRef.current?.scrollTo({
|
||||
y: Math.min(scrollOffset.current + hidden, top),
|
||||
animated: true
|
||||
})
|
||||
}
|
||||
}
|
||||
const scrollViewProps = {
|
||||
ref: scrollRef,
|
||||
onLayout: onViewportLayout,
|
||||
onScroll,
|
||||
scrollEventThrottle: 16
|
||||
}
|
||||
return {
|
||||
scrollRef,
|
||||
inputRef,
|
||||
revealReply,
|
||||
onViewportLayout,
|
||||
scrollViewProps,
|
||||
revealContent
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
|
||||
import { publishPageDeviceStore } from '../../mobile-web-shell/bridge/page-device-store'
|
||||
import { emitPageAppInactive } from '../../mobile-web-shell/bridge/bridge-app-inactive'
|
||||
import { noteChatTranscript } from './mobile-native-chat-transcript-writer'
|
||||
|
||||
function message(id: string): NativeChatMessage {
|
||||
return {
|
||||
id,
|
||||
role: 'assistant',
|
||||
blocks: [{ type: 'text', text: id }],
|
||||
timestamp: 1,
|
||||
source: 'transcript'
|
||||
}
|
||||
}
|
||||
|
||||
describe('chat copies when the app leaves the foreground', () => {
|
||||
const writes: string[] = []
|
||||
|
||||
beforeEach(() => {
|
||||
writes.length = 0
|
||||
publishPageDeviceStore({
|
||||
available: () => true,
|
||||
read: async (_table, keys) => ({ status: 'ok', values: keys.map(() => null) }),
|
||||
write: async (_table, ops) => {
|
||||
writes.push(...ops.map((op) => op.key))
|
||||
return { written: true }
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
publishPageDeviceStore(null)
|
||||
})
|
||||
|
||||
function note(rows: NativeChatMessage[]): void {
|
||||
noteChatTranscript(
|
||||
'chat-leaving',
|
||||
rows,
|
||||
() => true,
|
||||
(savedAt) => ({
|
||||
kind: 'terminal',
|
||||
savedAt,
|
||||
messages: rows,
|
||||
hasMore: false,
|
||||
beforeOffset: null
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
it('saves new rows on leaving and writes nothing when a flap brings none', async () => {
|
||||
vi.useFakeTimers()
|
||||
const [m1, m2, m3] = [message('m1'), message('m2'), message('m3')]
|
||||
note([m1, m2, m3])
|
||||
emitPageAppInactive()
|
||||
await vi.runAllTimersAsync()
|
||||
expect(writes).toHaveLength(1)
|
||||
|
||||
// Two minutes later, Notification Centre and back: the rows on screen are a new list with the same rows.
|
||||
vi.setSystemTime(Date.now() + 120_000)
|
||||
note([m1, m2, m3])
|
||||
emitPageAppInactive()
|
||||
note([m1, m2, m3])
|
||||
emitPageAppInactive()
|
||||
await vi.runAllTimersAsync()
|
||||
expect(writes).toHaveLength(1)
|
||||
|
||||
// A middle row changed (a tool result landed), with the last row the same.
|
||||
note([m1, { ...m2, blocks: [{ type: 'text', text: 'm2 with its result' }] }, m3])
|
||||
emitPageAppInactive()
|
||||
await vi.runAllTimersAsync()
|
||||
expect(writes).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
+70
@@ -2,11 +2,18 @@ import { createElement, type ReactNode } from 'react'
|
||||
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import type { AgentJournalStatusItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
|
||||
import { isAdmissibleAgentJournalItemBody } from '../../../../../src/shared/agent-session/journal/agent-session-journal-schemas'
|
||||
import { projectStructuredItemToNativeChat } from '../../../../../src/shared/agent-session/view/structured-agent-session-projection'
|
||||
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
|
||||
import { agentSessionFailureFact } from '../../../../../src/shared/agent-session/failures/agent-session-failure'
|
||||
import { agentSessionFailureWords } from '../../../../../src/shared/agent-session/failures/agent-session-failure-words'
|
||||
import { colors } from '../../../theme/mobile-theme'
|
||||
import { activateMobileUiLocale } from '../../../i18n/mobile-i18n'
|
||||
import { MarkdownLinkHandlerContext } from '../../../components/markdown-link-handler'
|
||||
import {
|
||||
MobileNativeChatNoticeContext,
|
||||
type MobileNativeChatNoticeView
|
||||
} from '../../mobile-native-chat-notice-context'
|
||||
|
||||
vi.mock('react-native', async () => {
|
||||
const React = await import('react')
|
||||
@@ -95,6 +102,69 @@ describe('MobileNativeChatMessage status notices', () => {
|
||||
observedAt: 2,
|
||||
body
|
||||
})!
|
||||
const renderNotice = (body: AgentJournalStatusItem, names: MobileNativeChatNoticeView) => {
|
||||
act(() => {
|
||||
renderer = create(
|
||||
createElement(
|
||||
MobileNativeChatNoticeContext.Provider,
|
||||
{ value: names },
|
||||
createElement(MobileNativeChatMessage, { message: statusRow(body) })
|
||||
)
|
||||
)
|
||||
})
|
||||
return renderer!.root.findAll(
|
||||
(node) => String(node.type) === 'Text' && node.props.selectable === true
|
||||
)[0]!
|
||||
}
|
||||
|
||||
it('localizes a canonical failure and discloses its diagnostic only on request', async () => {
|
||||
await activateMobileUiLocale('fr')
|
||||
const diagnostic = 'Internal provider diagnostic: modelNotFound'
|
||||
const notice = renderNotice(
|
||||
{
|
||||
kind: 'status',
|
||||
tone: 'error',
|
||||
...agentSessionFailureWords(agentSessionFailureFact('modelUnavailable'), {
|
||||
agentName: 'Codex',
|
||||
surface: 'row'
|
||||
}),
|
||||
providerFrame: {
|
||||
provider: 'codex',
|
||||
kind: 'notification:error',
|
||||
payload: {
|
||||
head: diagnostic,
|
||||
byteLength: diagnostic.length,
|
||||
digest: 'fixture',
|
||||
truncated: false
|
||||
}
|
||||
}
|
||||
},
|
||||
{ hostName: null, agentName: 'Codex' }
|
||||
)
|
||||
expect(String(notice.props.children)).toContain('le modèle sélectionné')
|
||||
expect(String(notice.props.children)).not.toContain(diagnostic)
|
||||
const details = () =>
|
||||
renderer!.root.findAll(
|
||||
(node) => String(node.type) === 'Text' && String(node.props.children).includes(diagnostic)
|
||||
)
|
||||
expect(details()).toHaveLength(0)
|
||||
const disclosure = renderer!.root.find(
|
||||
(node) => String(node.type) === 'Pressable' && node.props['aria-expanded'] === false
|
||||
)
|
||||
act(() => disclosure.props.onPress())
|
||||
expect(details().length).toBeGreaterThan(0)
|
||||
act(() => renderer?.unmount())
|
||||
const hostAdvice: unknown = {
|
||||
kind: 'status',
|
||||
text: 'Custom host advice: use the enterprise model.',
|
||||
failure: agentSessionFailureFact('modelUnavailable')
|
||||
}
|
||||
if (!isAdmissibleAgentJournalItemBody(hostAdvice) || hostAdvice.kind !== 'status') {
|
||||
throw new Error('Expected host status row')
|
||||
}
|
||||
const custom = renderNotice(hostAdvice, { hostName: null, agentName: 'Codex' })
|
||||
expect(custom.props.children).toBe('Custom host advice: use the enterprise model.')
|
||||
})
|
||||
|
||||
it('links a CI result line to its pull request and commit through the link sheet', () => {
|
||||
const openLink = vi.fn()
|
||||
|
||||
@@ -73,7 +73,15 @@ function noticeLineText(
|
||||
// Only reword text fully described by its fact; other host text stays as written.
|
||||
const context = { agentName: names.agentName }
|
||||
const surface =
|
||||
failure?.kind === 'savedConversationMissing' || failure?.kind === 'pluginInputRequired'
|
||||
failure &&
|
||||
[
|
||||
'savedConversationMissing',
|
||||
'pluginInputRequired',
|
||||
'modelUnavailable',
|
||||
'providerUnavailable',
|
||||
'providerSafetyStopped',
|
||||
'providerResponseFailed'
|
||||
].includes(failure.kind)
|
||||
? (['row', 'rejection'] as const).find(
|
||||
(candidate) => notice.text === agentSessionFailureSentence(failure, candidate, context)
|
||||
)
|
||||
|
||||
@@ -15,10 +15,11 @@ import {
|
||||
withMobileNativeChatHarness
|
||||
} from './mobile-native-chat-projection-sources'
|
||||
import {
|
||||
buildMobileNativeChatUnit,
|
||||
groupMobileNativeChatUnitMembers,
|
||||
type Unit
|
||||
} from './mobile-native-chat-projection-units'
|
||||
buildNativeChatFoldUnit,
|
||||
groupNativeChatFoldUnitMembers,
|
||||
type NativeChatFoldUnit as Unit
|
||||
} from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units'
|
||||
import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data'
|
||||
|
||||
// A tail harness row that is its own image unit and no roster member leaves every earlier unit as it was.
|
||||
function staysInTail(harness: NativeChatMessage): boolean {
|
||||
@@ -109,9 +110,15 @@ export function projectMobileNativeChatTail(
|
||||
rescan.push(...newRows)
|
||||
// Orphan names depend on every earlier id, so a re-projected unit with orphans takes the full pass.
|
||||
const rebuilt: Unit[] = []
|
||||
for (const members of groupMobileNativeChatUnitMembers(rescan, kinds)) {
|
||||
for (const members of groupNativeChatFoldUnitMembers(rescan, kinds)) {
|
||||
const held = previous.units.findLast((unit) => unit.sources[0]!.id === members[0]!.id)
|
||||
const unit = buildMobileNativeChatUnit(members, NO_IDS, kinds, held)
|
||||
const unit = buildNativeChatFoldUnit(
|
||||
members,
|
||||
NO_IDS,
|
||||
kinds,
|
||||
held,
|
||||
finishMobileNativeChatMessages
|
||||
)
|
||||
if (unit !== held && unit.orphans.length > 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -1,135 +0,0 @@
|
||||
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
|
||||
import {
|
||||
foldToolMessages,
|
||||
type NativeChatToolFoldKind
|
||||
} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold'
|
||||
import {
|
||||
orphanRowId,
|
||||
type NativeChatOrphanOrigin
|
||||
} from '../../../../../src/shared/native-chat/tools/native-chat-folded-tool-results'
|
||||
import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data'
|
||||
|
||||
export type Unit = {
|
||||
sources: readonly NativeChatMessage[]
|
||||
rows: NativeChatMessage[]
|
||||
orphans: readonly NativeChatOrphanOrigin[]
|
||||
}
|
||||
|
||||
export function groupMobileNativeChatUnitMembers(
|
||||
grouped: readonly NativeChatMessage[],
|
||||
kinds: ReadonlyMap<NativeChatMessage, NativeChatToolFoldKind>
|
||||
): NativeChatMessage[][] {
|
||||
const members: NativeChatMessage[][] = []
|
||||
let active = false
|
||||
for (const source of grouped) {
|
||||
const kind = kinds.get(source)!
|
||||
if (active && (kind === 'tool' || kind === 'sidecar' || kind === 'pass')) {
|
||||
members.at(-1)!.push(source)
|
||||
} else {
|
||||
members.push([source])
|
||||
active = source.role === 'assistant' && kind !== 'orphan'
|
||||
}
|
||||
}
|
||||
return members
|
||||
}
|
||||
|
||||
export function buildMobileNativeChatUnit(
|
||||
sources: readonly NativeChatMessage[],
|
||||
ids: ReadonlySet<string>,
|
||||
kinds: ReadonlyMap<NativeChatMessage, NativeChatToolFoldKind>,
|
||||
before: Unit | undefined
|
||||
): Unit {
|
||||
if (
|
||||
before &&
|
||||
before.sources.length === sources.length &&
|
||||
before.sources.every((source, index) => source === sources[index])
|
||||
) {
|
||||
return before
|
||||
}
|
||||
const substituted = before && substituteProse(before, sources, kinds)
|
||||
const orphans: NativeChatOrphanOrigin[] = []
|
||||
const rows =
|
||||
substituted ??
|
||||
finishMobileNativeChatMessages(
|
||||
foldToolMessages(sources, ids, kinds, (origin) => orphans.push(origin))
|
||||
)
|
||||
return { sources, rows, orphans: substituted ? before!.orphans : orphans }
|
||||
}
|
||||
|
||||
export function buildMobileNativeChatUnits(
|
||||
grouped: readonly NativeChatMessage[],
|
||||
kinds: ReadonlyMap<NativeChatMessage, NativeChatToolFoldKind>,
|
||||
previous?: { units: readonly Unit[] }
|
||||
): Unit[] {
|
||||
const ids = new Set(grouped.map((row) => row.id))
|
||||
const oldUnits = new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit]))
|
||||
const units = groupMobileNativeChatUnitMembers(grouped, kinds).map((sources) =>
|
||||
buildMobileNativeChatUnit(sources, ids, kinds, oldUnits.get(sources[0]!.id))
|
||||
)
|
||||
const allocated = new Set(ids)
|
||||
const occurrences = new Map<string, number>()
|
||||
return units.map((unit) => {
|
||||
const renamed = new Map<NativeChatMessage, NativeChatMessage>()
|
||||
const orphans = unit.orphans.map((origin) => {
|
||||
const id = orphanRowId(origin.sourceId, allocated, occurrences)
|
||||
allocated.add(id)
|
||||
if (id === origin.row.id) {
|
||||
return origin
|
||||
}
|
||||
const row = { ...origin.row, id }
|
||||
renamed.set(origin.row, row)
|
||||
return { ...origin, row }
|
||||
})
|
||||
return renamed.size === 0
|
||||
? unit
|
||||
: {
|
||||
...unit,
|
||||
orphans,
|
||||
rows: unit.rows.map((row) => renamed.get(row) ?? row)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function substituteProse(
|
||||
before: Unit,
|
||||
sources: readonly NativeChatMessage[],
|
||||
kinds: ReadonlyMap<NativeChatMessage, NativeChatToolFoldKind>
|
||||
): NativeChatMessage[] | null {
|
||||
if (before.sources.length !== sources.length) {
|
||||
return null
|
||||
}
|
||||
const changed = sources.flatMap((source, index) =>
|
||||
source === before.sources[index] ? [] : [index]
|
||||
)
|
||||
if (changed.length !== 1 || changed[0] !== 0) {
|
||||
return null
|
||||
}
|
||||
const old = before.sources[0]!,
|
||||
next = sources[0]!
|
||||
if (
|
||||
old.role !== next.role ||
|
||||
(next.role !== 'assistant' && next.role !== 'reasoning') ||
|
||||
old.unpairedToolResults ||
|
||||
next.unpairedToolResults ||
|
||||
!old.blocks.every((block) => block.type === 'text' && !block.providerFrame) ||
|
||||
!next.blocks.every((block) => block.type === 'text' && !block.providerFrame)
|
||||
) {
|
||||
return null
|
||||
}
|
||||
const target = before.rows.find((row) => row.id === old.id && row.role === old.role)
|
||||
if (!target || !old.blocks.every((block, index) => block === target.blocks[index])) {
|
||||
return null
|
||||
}
|
||||
const contribution = sources
|
||||
.slice(1)
|
||||
.findLast(
|
||||
(source) =>
|
||||
source.journalPosition && (kinds.get(source) === 'tool' || kinds.get(source) === 'sidecar')
|
||||
)
|
||||
const replacement: NativeChatMessage = {
|
||||
...next,
|
||||
blocks: [...next.blocks, ...target.blocks.slice(old.blocks.length)],
|
||||
...(contribution ? { foldedJournalPosition: contribution.journalPosition } : {})
|
||||
}
|
||||
return before.rows.map((row) => (row === target ? replacement : row))
|
||||
}
|
||||
@@ -9,13 +9,19 @@ import {
|
||||
nativeChatImageTranscriptUnits,
|
||||
normalizeImageTranscriptUnit
|
||||
} from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers'
|
||||
import { foldMobileNativeChatMessages } from '../mobile-native-chat-render-data'
|
||||
import {
|
||||
finishMobileNativeChatMessages,
|
||||
foldMobileNativeChatMessages
|
||||
} from '../mobile-native-chat-render-data'
|
||||
import {
|
||||
prepareMobileNativeChatSources,
|
||||
type MobileNativeChatProjectionSource
|
||||
} from './mobile-native-chat-projection-sources'
|
||||
import { projectMobileNativeChatTail } from './mobile-native-chat-projection-tail'
|
||||
import { buildMobileNativeChatUnits, type Unit } from './mobile-native-chat-projection-units'
|
||||
import {
|
||||
buildNativeChatFoldUnits,
|
||||
type NativeChatFoldUnit as Unit
|
||||
} from '../../../../../src/shared/native-chat/transcript/native-chat-fold-units'
|
||||
|
||||
type ImageUnit = { sources: readonly NativeChatMessage[]; rows: NativeChatMessage[] }
|
||||
export type MobileNativeChatProjection = {
|
||||
@@ -75,7 +81,12 @@ export function projectMobileNativeChatMessages(
|
||||
const kinds = new Map(
|
||||
grouped.map((source) => [source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)])
|
||||
)
|
||||
const units = buildMobileNativeChatUnits(grouped, kinds, previous)
|
||||
const units = buildNativeChatFoldUnits(
|
||||
grouped,
|
||||
kinds,
|
||||
new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])),
|
||||
finishMobileNativeChatMessages
|
||||
)
|
||||
const unchanged =
|
||||
previous &&
|
||||
units.length === previous.units.length &&
|
||||
|
||||
@@ -5,7 +5,10 @@ import { useEffect, useRef, useCallback, useState } from 'react'
|
||||
import { AppState, type AppStateStatus, Platform } from 'react-native'
|
||||
import { useFocusEffect } from 'expo-router'
|
||||
import { loadHosts } from '../transport/hosts/host-store'
|
||||
import { loadTerminalAccessoryLayout } from '../terminal/terminal-accessory-layout'
|
||||
import {
|
||||
loadTerminalAccessoryLayout,
|
||||
saveTerminalSmartRail
|
||||
} from '../terminal/terminal-accessory-layout'
|
||||
import {
|
||||
recoverActiveTerminalAfterForeground,
|
||||
shouldRecoverTerminalOnAppStateChange
|
||||
@@ -25,6 +28,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM
|
||||
setCustomKeys,
|
||||
setVisibleBuiltInIds,
|
||||
setDirectionPadEnabled,
|
||||
setSmartRailEnabled,
|
||||
setHostEndpoint,
|
||||
setHostName,
|
||||
connStateRef,
|
||||
@@ -101,6 +105,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM
|
||||
if (layout) {
|
||||
setVisibleBuiltInIds(layout.visibleBuiltInIds)
|
||||
setDirectionPadEnabled(layout.directionPadEnabled !== false)
|
||||
setSmartRailEnabled(layout.smartRail === true)
|
||||
}
|
||||
setAccessoryLayoutLoaded(true)
|
||||
}
|
||||
@@ -112,6 +117,19 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM
|
||||
}
|
||||
}, [padAvailable, shellStorage])
|
||||
|
||||
const handleSmartRailChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
// A read that started before the toggle must not flip it back.
|
||||
layoutReadRevisionRef.current += 1
|
||||
setSmartRailEnabled(enabled)
|
||||
saveTerminalSmartRail(enabled, padAvailable).catch((error: unknown) => {
|
||||
console.warn('[terminal-keys] the store would not take the Smart rail setting', error)
|
||||
setSmartRailEnabled(!enabled)
|
||||
})
|
||||
},
|
||||
[padAvailable]
|
||||
)
|
||||
|
||||
useFocusEffect(
|
||||
useCallback(() => {
|
||||
const releaseKeys = refreshCustomKeys()
|
||||
@@ -195,6 +213,7 @@ export function useMobileSessionLifecycle(scope: MobileSessionTabReconciliationM
|
||||
}, [connState, scheduleDelayedAction, subscribeToTerminal, terminalResume, unsubscribeTerminal])
|
||||
return {
|
||||
accessoryPreferencesReady: customKeysLoaded && accessoryLayoutLoaded,
|
||||
handleSmartRailChange,
|
||||
pendingForegroundRecoveryRef
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,6 +82,7 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
|
||||
const [renameTarget, setRenameTarget] = useState<Terminal | null>(null)
|
||||
const [customKeys, setCustomKeys] = useState<CustomKey[]>([])
|
||||
const [directionPadEnabled, setDirectionPadEnabled] = useState(true)
|
||||
const [smartRailEnabled, setSmartRailEnabled] = useState(false)
|
||||
const [visibleBuiltInIds, setVisibleBuiltInIds] = useState<string[]>(
|
||||
getDefaultTerminalAccessoryBuiltInIds
|
||||
)
|
||||
@@ -182,6 +183,8 @@ export function useMobileSessionScreenState(scope: MobileSessionFoundationModel)
|
||||
setCustomKeys,
|
||||
directionPadEnabled,
|
||||
setDirectionPadEnabled,
|
||||
smartRailEnabled,
|
||||
setSmartRailEnabled,
|
||||
visibleBuiltInIds,
|
||||
setVisibleBuiltInIds,
|
||||
showCustomKeyModal,
|
||||
|
||||
@@ -5,7 +5,8 @@ import {
|
||||
latestAgentSessionContextClearSequence
|
||||
} from '../../../src/shared/agent-session/agent-session-context-clear'
|
||||
import type { StructuredAgentSessionState } from '../../../src/shared/agent-session/structured-agent-session-reducer'
|
||||
import { projectStructuredAgentSessionMessages } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection'
|
||||
import type { StructuredAgentSessionOptimisticMessage } from '../../../src/shared/agent-session/view/structured-agent-session-message-projection'
|
||||
import { createStructuredAgentSessionMessageProjection } from '../../../src/shared/agent-session/view/structured-agent-session-message-stream'
|
||||
import { tuiAgentDisplayName } from '../../../src/shared/agent-launch/catalog/tui-agent-display-names'
|
||||
import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice'
|
||||
import { omitNativeChatThreadGoalRows } from '../../../src/shared/native-chat/transcript/native-chat-thread-goal-rows'
|
||||
@@ -22,7 +23,7 @@ const mobileStructuredTranscript = createStructuredQuestionProjection(
|
||||
export function useMobileStructuredTranscript(
|
||||
agent: string | null,
|
||||
state: Pick<StructuredAgentSessionState, 'epoch' | 'items' | 'submissions'>,
|
||||
optimistic: Parameters<typeof projectStructuredAgentSessionMessages>[1],
|
||||
optimistic: readonly StructuredAgentSessionOptimisticMessage[],
|
||||
sessionKey: string
|
||||
) {
|
||||
const [clearSent, setClearSent] = useState<{
|
||||
@@ -61,24 +62,22 @@ export function useMobileStructuredTranscript(
|
||||
}),
|
||||
[agent, floor, state.items]
|
||||
)
|
||||
const projectMessages = useMemo(
|
||||
() => createStructuredAgentSessionMessageProjection(mobileStructuredTranscript.messages),
|
||||
[]
|
||||
)
|
||||
const questionTranscript = useMemo(() => mobileStructuredTranscript.stream(), [])
|
||||
const messages = useMemo(
|
||||
() =>
|
||||
// The goal strip on the composer shows goal state, as on desktop.
|
||||
omitNativeChatThreadGoalRows(
|
||||
projectStructuredAgentSessionMessages(
|
||||
transcriptItems,
|
||||
optimistic,
|
||||
state.submissions,
|
||||
mobileStructuredTranscript.messages
|
||||
)
|
||||
),
|
||||
[transcriptItems, optimistic, state.submissions]
|
||||
omitNativeChatThreadGoalRows(projectMessages(transcriptItems, optimistic, state.submissions)),
|
||||
[transcriptItems, optimistic, state.submissions, projectMessages]
|
||||
)
|
||||
return {
|
||||
clearing,
|
||||
onClearSent,
|
||||
transcriptItems,
|
||||
messages,
|
||||
receipts: mobileStructuredTranscript.transcript(transcriptItems).receipts
|
||||
receipts: questionTranscript(transcriptItems).receipts
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,17 @@ import { styles as sessionStyles } from '../../session/mobile-session-styles'
|
||||
import { useKeyboardPersistingTaps } from '../../platform/keyboard-persisting-taps'
|
||||
import type { MobileSessionController } from '../../session/use-mobile-session-controller'
|
||||
import { useMobileSessionKeyboardLift } from './use-mobile-session-keyboard-lift'
|
||||
import {
|
||||
AGENT_SMART_KEY_STEP_MS,
|
||||
type AgentSmartKey
|
||||
} from '../../../../src/shared/terminal/input/agent-smart-keys'
|
||||
import type { TerminalAccessoryKey } from '../terminal-accessory-keys'
|
||||
import { resolveMobileTerminalTabSmartKeys } from './mobile-terminal-tab-agent'
|
||||
import { MobileSessionSmartKeys } from './MobileSessionSmartKeys'
|
||||
import { MobileSessionLatchKeys } from './MobileSessionLatchKeys'
|
||||
import { isAccessibilityClick, useTerminalKeyRowTouch } from './use-terminal-key-row-touch'
|
||||
|
||||
type PreparedPress = ReturnType<MobileSessionController['prepareAccessoryPress']>
|
||||
|
||||
// The terminal's key row above the live input; every key goes straight to the terminal.
|
||||
export function MobileSessionAccessoryKeys({
|
||||
@@ -46,10 +57,26 @@ export function MobileSessionAccessoryKeys({
|
||||
stopAccessoryRepeat,
|
||||
cancelAccessoryRepeat,
|
||||
prepareAccessoryPress,
|
||||
handlePaste
|
||||
handlePaste,
|
||||
dockKeys,
|
||||
activeSessionTab,
|
||||
terminals,
|
||||
smartRailEnabled
|
||||
} = controller
|
||||
const keyboardLift = useMobileSessionKeyboardLift(controller.dockBottomInset)
|
||||
const accessoryPresses = useRef(new Map<string, ReturnType<typeof prepareAccessoryPress>>())
|
||||
const accessoryPresses = useRef(new Map<string, PreparedPress>())
|
||||
const scrollRef = useRef<ScrollView>(null)
|
||||
const latestSmartKeys = useMemo(
|
||||
() =>
|
||||
smartRailEnabled ? resolveMobileTerminalTabSmartKeys(activeSessionTab, terminals) : null,
|
||||
[smartRailEnabled, activeSessionTab, terminals]
|
||||
)
|
||||
const touch = useTerminalKeyRowTouch({
|
||||
scrollRef,
|
||||
latest: latestSmartKeys,
|
||||
cancelAccessoryRepeat
|
||||
})
|
||||
const smartKeys = touch.shown
|
||||
const keepsKeyboard = useKeyboardPersistingTaps('always')
|
||||
// An unmounting Pressable never fires onPressOut, so a held key would outlive its row.
|
||||
useEffect(() => cancelAccessoryRepeat, [cancelAccessoryRepeat])
|
||||
@@ -70,8 +97,57 @@ export function MobileSessionAccessoryKeys({
|
||||
]
|
||||
const sendKeyLabel = (label: string) =>
|
||||
t('session.accessoryKeys.sendKey', 'Send {{label}}', { label })
|
||||
// Held Shift, Ctrl or Alt turn a key into its combo and are used up when it sends; keys that take none send as they are.
|
||||
const prepareBuiltInPress = (key: TerminalAccessoryKey): PreparedPress => {
|
||||
const chord = dockKeys.chordInput(key.id)
|
||||
const press = prepareAccessoryPress(chord ?? createTerminalLiveAccessoryInput(key))
|
||||
const takeChord = () => {
|
||||
if (chord) {
|
||||
dockKeys.takeModifiers()
|
||||
}
|
||||
}
|
||||
return {
|
||||
tap: () => {
|
||||
takeChord()
|
||||
return press.tap()
|
||||
},
|
||||
hold: (firstRepeatDelayMs) => {
|
||||
takeChord()
|
||||
press.hold(firstRepeatDelayMs)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Later writes belong to the same press, so a scroll after release mustn't drop them; a tab switch does.
|
||||
const sendSmartKey = (key: AgentSmartKey) => {
|
||||
const handle = controller.activeHandleRef.current
|
||||
void (async () => {
|
||||
for (const [index, bytes] of key.writes.entries()) {
|
||||
if (index > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, AGENT_SMART_KEY_STEP_MS))
|
||||
}
|
||||
if (controller.activeHandleRef.current !== handle) {
|
||||
return
|
||||
}
|
||||
if (!(await prepareAccessoryPress({ bytes }).tap())) {
|
||||
return
|
||||
}
|
||||
}
|
||||
})()
|
||||
}
|
||||
const latchIndex = builtInKeys.findIndex((key) => key.id === 'tab') + 1
|
||||
const latchKeys = (
|
||||
<MobileSessionLatchKeys
|
||||
key="latches"
|
||||
modifiers={dockKeys.modifiers}
|
||||
disabled={!canSend}
|
||||
onPressIn={() => touch.arm('latch')}
|
||||
onPress={(modifier, event) =>
|
||||
touch.fire('latch', event, () => dockKeys.tapModifier(modifier))
|
||||
}
|
||||
/>
|
||||
)
|
||||
return (
|
||||
<View ref={keepsKeyboard} style={styles.keyRow}>
|
||||
<View ref={keepsKeyboard} style={styles.keyRow} {...touch.rowTouchHandlers}>
|
||||
{/* Why: fixed keyboard escape hatch; outside the ScrollView so it can't scroll away (#5106). */}
|
||||
{keyboardLift > 0 && (
|
||||
<Pressable
|
||||
@@ -98,23 +174,36 @@ export function MobileSessionAccessoryKeys({
|
||||
)}
|
||||
{/* Why: default tap handling makes the first key tap dismiss the keyboard and get swallowed (#5106). */}
|
||||
<ScrollView
|
||||
ref={scrollRef}
|
||||
style={styles.keyScroll}
|
||||
horizontal
|
||||
showsHorizontalScrollIndicator={false}
|
||||
showsVerticalScrollIndicator={false}
|
||||
contentContainerStyle={styles.keyScrollContent}
|
||||
keyboardShouldPersistTaps="always"
|
||||
onScrollBeginDrag={cancelAccessoryRepeat}
|
||||
onScroll={touch.onScroll}
|
||||
scrollEventThrottle={16}
|
||||
>
|
||||
{smartKeys ? (
|
||||
<MobileSessionSmartKeys
|
||||
keySet={smartKeys}
|
||||
disabled={!canSend}
|
||||
onPressIn={(key) => touch.arm(`smart:${key.id}`)}
|
||||
onPress={(key, event) => touch.fire(`smart:${key.id}`, event, () => sendSmartKey(key))}
|
||||
/>
|
||||
) : null}
|
||||
<Pressable
|
||||
style={keyStyle}
|
||||
disabled={!canSend}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPress={() => {
|
||||
if (activeHandle) {
|
||||
void toggleDisplayMode(activeHandle)
|
||||
}
|
||||
}}
|
||||
onPressIn={() => touch.arm('displayMode')}
|
||||
onPress={(event) =>
|
||||
touch.fire('displayMode', event, () => {
|
||||
if (activeHandle) {
|
||||
void toggleDisplayMode(activeHandle)
|
||||
}
|
||||
})
|
||||
}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
phoneDisplay
|
||||
@@ -133,7 +222,8 @@ export function MobileSessionAccessoryKeys({
|
||||
style={keyStyle}
|
||||
disabled={!canSend}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPress={() => void handlePaste()}
|
||||
onPressIn={() => touch.arm('paste')}
|
||||
onPress={(event) => touch.fire('paste', event, () => void handlePaste())}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t(
|
||||
'session.accessoryKeys.pasteFromClipboard',
|
||||
@@ -143,20 +233,22 @@ export function MobileSessionAccessoryKeys({
|
||||
<Text style={styles.keyText}>{t('session.accessoryKeys.paste', 'Paste')}</Text>
|
||||
</Pressable>
|
||||
)}
|
||||
{builtInKeys.map((key) => (
|
||||
{latchIndex === 0 ? latchKeys : null}
|
||||
{builtInKeys.flatMap((key, index) => [
|
||||
<Pressable
|
||||
key={key.id}
|
||||
style={keyStyle}
|
||||
disabled={!canSend}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPressIn={(event) => {
|
||||
touch.arm(key.id)
|
||||
if (!key.repeatable) {
|
||||
return
|
||||
}
|
||||
const press = prepareAccessoryPress(createTerminalLiveAccessoryInput(key))
|
||||
accessoryPresses.current.set(key.id, press)
|
||||
const prepared = prepareBuiltInPress(key)
|
||||
accessoryPresses.current.set(key.id, prepared)
|
||||
if (event.type === 'keydown') {
|
||||
press.hold(TERMINAL_ACCESSORY_REPEAT_DELAY_MS)
|
||||
prepared.hold(TERMINAL_ACCESSORY_REPEAT_DELAY_MS)
|
||||
}
|
||||
}}
|
||||
onPressOut={() => {
|
||||
@@ -165,23 +257,23 @@ export function MobileSessionAccessoryKeys({
|
||||
}
|
||||
}}
|
||||
onPress={(event) => {
|
||||
if (key.repeatable) {
|
||||
// Accessibility clicks have no touch-down to prepare a sender.
|
||||
const accessibilityClick =
|
||||
event.type === 'click' &&
|
||||
'detail' in event.nativeEvent &&
|
||||
event.nativeEvent.detail === 0
|
||||
const press =
|
||||
(!accessibilityClick && accessoryPresses.current.get(key.id)) ||
|
||||
prepareAccessoryPress(createTerminalLiveAccessoryInput(key))
|
||||
accessoryPresses.current.delete(key.id)
|
||||
void press.tap()
|
||||
return
|
||||
}
|
||||
void handleAccessoryKey(createTerminalLiveAccessoryInput(key))
|
||||
// Accessibility clicks have no touch-down to prepare a sender.
|
||||
const prepared =
|
||||
(key.repeatable &&
|
||||
!isAccessibilityClick(event) &&
|
||||
accessoryPresses.current.get(key.id)) ||
|
||||
prepareBuiltInPress(key)
|
||||
accessoryPresses.current.delete(key.id)
|
||||
touch.fire(key.id, event, () => void prepared.tap())
|
||||
}}
|
||||
onLongPress={
|
||||
key.repeatable ? () => accessoryPresses.current.get(key.id)?.hold() : undefined
|
||||
key.repeatable
|
||||
? () => {
|
||||
if (touch.stillArmed(key.id)) {
|
||||
accessoryPresses.current.get(key.id)?.hold()
|
||||
}
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
delayLongPress={TERMINAL_ACCESSORY_REPEAT_DELAY_MS}
|
||||
// A web <button> clicks on Enter keydown as well, which would send a held key twice.
|
||||
@@ -189,15 +281,19 @@ export function MobileSessionAccessoryKeys({
|
||||
accessibilityLabel={key.accessibilityLabel ?? sendKeyLabel(key.label)}
|
||||
>
|
||||
<Text style={styles.keyText}>{key.label}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</Pressable>,
|
||||
index + 1 === latchIndex ? latchKeys : null
|
||||
])}
|
||||
{customKeys.map((key) => (
|
||||
<Pressable
|
||||
key={key.id}
|
||||
style={({ pressed }) => [...keyStyle({ pressed }), styles.customKey]}
|
||||
disabled={!canSend}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPress={() => void handleAccessoryKey({ bytes: key.bytes })}
|
||||
onPressIn={() => touch.arm(key.id)}
|
||||
onPress={(event) =>
|
||||
touch.fire(key.id, event, () => void handleAccessoryKey({ bytes: key.bytes }))
|
||||
}
|
||||
onLongPress={() => {
|
||||
triggerMediumImpact()
|
||||
setDeleteKeyTarget(key)
|
||||
@@ -216,7 +312,8 @@ export function MobileSessionAccessoryKeys({
|
||||
<Pressable
|
||||
style={({ pressed }) => [styles.key, pressed && styles.keyPressed]}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPress={() => setShowCustomKeyModal(true)}
|
||||
onPressIn={() => touch.arm('addKey')}
|
||||
onPress={(event) => touch.fire('addKey', event, () => setShowCustomKeyModal(true))}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t('session.accessoryKeys.addCustomShortcut', 'Add custom shortcut')}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import { Pressable, Text, type GestureResponderEvent } from 'react-native'
|
||||
import type { TerminalShortcutModifier } from '../terminal-accessory-keys'
|
||||
import type { StickyModifiers } from '../terminal-sticky-modifiers'
|
||||
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
|
||||
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
|
||||
import { TERMINAL_KEY_HIT_SLOP, terminalDockStyles as styles } from './terminal-dock-styles'
|
||||
|
||||
const LATCHES: readonly { id: TerminalShortcutModifier; label: string }[] = [
|
||||
{ id: 'shift', label: 'Shift' },
|
||||
{ id: 'ctrl', label: 'Ctrl' },
|
||||
{ id: 'alt', label: 'Alt' }
|
||||
]
|
||||
|
||||
/** Shift, Ctrl and Alt on the key row: a tap holds one for the next key, a double tap locks it. */
|
||||
export function MobileSessionLatchKeys({
|
||||
modifiers,
|
||||
disabled,
|
||||
onPressIn,
|
||||
onPress
|
||||
}: {
|
||||
modifiers: StickyModifiers
|
||||
disabled: boolean
|
||||
onPressIn: () => void
|
||||
onPress: (modifier: TerminalShortcutModifier, event: GestureResponderEvent) => void
|
||||
}) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
const names: Record<TerminalShortcutModifier, string> = {
|
||||
shift: t('session.accessoryKeys.shift', 'Shift'),
|
||||
ctrl: t('session.accessoryKeys.control', 'Control'),
|
||||
alt: t('session.accessoryKeys.alt', 'Alt')
|
||||
}
|
||||
return LATCHES.map(({ id, label }) => {
|
||||
const latch = modifiers[id]
|
||||
return (
|
||||
<Pressable
|
||||
key={id}
|
||||
style={({ pressed }) => [
|
||||
styles.key,
|
||||
styles.keyLatch,
|
||||
latch === 'once' && styles.keyLatched,
|
||||
latch === 'locked' && styles.keyLocked,
|
||||
pressed && styles.keyPressed,
|
||||
disabled && styles.disabled
|
||||
]}
|
||||
disabled={disabled}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPressIn={onPressIn}
|
||||
onPress={(event) => onPress(id, event)}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={names[id]}
|
||||
accessibilityState={{ selected: latch !== 'off' }}
|
||||
>
|
||||
<Text style={[styles.keyText, latch === 'locked' && styles.keyTextLocked]}>{label}</Text>
|
||||
</Pressable>
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { Pressable, Text, View, type GestureResponderEvent } from 'react-native'
|
||||
import type {
|
||||
AgentSmartKey,
|
||||
AgentSmartKeyName,
|
||||
AgentSmartKeySet
|
||||
} from '../../../../src/shared/terminal/input/agent-smart-keys'
|
||||
import { MobileAgentIcon } from '../../components/MobileAgentIcon'
|
||||
import type { Translate } from '../../i18n/mobile-i18n'
|
||||
import { useMobileTranslation } from '../../i18n/use-mobile-translation'
|
||||
import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme'
|
||||
import { TERMINAL_KEY_HIT_SLOP, terminalDockStyles as styles } from './terminal-dock-styles'
|
||||
|
||||
function smartKeyWord(t: Translate, name: AgentSmartKeyName): string {
|
||||
switch (name) {
|
||||
case 'stop':
|
||||
return t('session.smartKeys.stop', 'Stop')
|
||||
case 'sendNow':
|
||||
return t('session.smartKeys.sendNow', 'Send now')
|
||||
case 'background':
|
||||
return t('session.smartKeys.background', 'Background')
|
||||
case 'mode':
|
||||
return t('session.smartKeys.mode', 'Mode')
|
||||
case 'yes':
|
||||
return t('session.smartKeys.yes', 'Yes')
|
||||
case 'always':
|
||||
return t('session.smartKeys.always', 'Always')
|
||||
case 'no':
|
||||
return t('session.smartKeys.no', 'No')
|
||||
case 'cancel':
|
||||
return t('session.smartKeys.cancel', 'Cancel')
|
||||
case 'history':
|
||||
return t('session.smartKeys.history', 'History')
|
||||
case 'rewind':
|
||||
return t('session.smartKeys.rewind', 'Rewind')
|
||||
case 'queue':
|
||||
return t('session.smartKeys.queue', 'Queue')
|
||||
case 'edit':
|
||||
return t('session.smartKeys.edit', 'Edit')
|
||||
case 'answer':
|
||||
return t('session.smartKeys.answer', 'Answer')
|
||||
case 'skip':
|
||||
return t('session.smartKeys.skip', 'Skip')
|
||||
case 'confirm':
|
||||
return t('session.smartKeys.confirm', 'Confirm')
|
||||
case 'reject':
|
||||
return t('session.smartKeys.reject', 'Reject')
|
||||
}
|
||||
}
|
||||
|
||||
/** The agent's keys for its current state, in a capsule at the front of the key row. */
|
||||
export function MobileSessionSmartKeys({
|
||||
keySet,
|
||||
disabled,
|
||||
onPressIn,
|
||||
onPress
|
||||
}: {
|
||||
keySet: AgentSmartKeySet
|
||||
disabled: boolean
|
||||
onPressIn: (key: AgentSmartKey) => void
|
||||
onPress: (key: AgentSmartKey, event: GestureResponderEvent) => void
|
||||
}) {
|
||||
useMobileColorScheme()
|
||||
const t = useMobileTranslation()
|
||||
return (
|
||||
<>
|
||||
<View style={styles.smartGroup}>
|
||||
<MobileAgentIcon agentId={keySet.agentId} size={13} />
|
||||
{keySet.keys.map((key) => {
|
||||
const word = key.name ? smartKeyWord(t, key.name) : null
|
||||
return (
|
||||
<Pressable
|
||||
key={key.id}
|
||||
style={({ pressed }) => [
|
||||
styles.key,
|
||||
key.primary && styles.smartKeyPrimary,
|
||||
pressed && styles.keyPressed,
|
||||
disabled && styles.disabled
|
||||
]}
|
||||
disabled={disabled}
|
||||
hitSlop={TERMINAL_KEY_HIT_SLOP}
|
||||
onPressIn={() => onPressIn(key)}
|
||||
onPress={(event) => onPress(key, event)}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
word
|
||||
? t('session.smartKeys.keyLabel', '{{word}}, sends {{combo}}', {
|
||||
word,
|
||||
combo: key.combo
|
||||
})
|
||||
: t('session.accessoryKeys.sendKey', 'Send {{label}}', { label: key.combo })
|
||||
}
|
||||
>
|
||||
{word ? (
|
||||
<View style={styles.smartKeyStack}>
|
||||
<Text style={[styles.smartKeyWord, key.primary && styles.smartKeyPrimaryText]}>
|
||||
{word}
|
||||
</Text>
|
||||
<Text style={[styles.smartKeyCombo, key.primary && styles.smartKeyPrimaryText]}>
|
||||
{key.combo}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<Text style={styles.keyText}>{key.combo}</Text>
|
||||
)}
|
||||
</Pressable>
|
||||
)
|
||||
})}
|
||||
</View>
|
||||
<View style={styles.smartDivider} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,10 @@ import { agentTypeToIconAgent } from '../../../../src/shared/agent-status/presen
|
||||
import { resolveTabAgentFromSignalSnapshot } from '../../../../src/shared/tab-agent-from-signals'
|
||||
import type { AgentStatusEntry } from '../../../../src/shared/agent-status/contracts/agent-status-types'
|
||||
import type { TuiAgent } from '../../../../src/shared/agent-launch/catalog/tui-agent'
|
||||
import {
|
||||
resolveAgentSmartKeys,
|
||||
type AgentSmartKeySet
|
||||
} from '../../../../src/shared/terminal/input/agent-smart-keys'
|
||||
import { isBlankBrowserUrl } from '../../browser/browser-url'
|
||||
import { translate } from '../../i18n/mobile-i18n'
|
||||
import type { MobileSessionTab } from '../../session/tabs/mobile-session-tabs'
|
||||
@@ -114,3 +118,20 @@ export function getMobileSessionTabTitle(
|
||||
}
|
||||
return tab.title || translate('session.terminalTabAgent.terminal', 'Terminal')
|
||||
}
|
||||
|
||||
/** The keys for what the tab's agent is doing now, or null for a shell, an unknown agent or state. */
|
||||
export function resolveMobileTerminalTabSmartKeys(
|
||||
tab: MobileSessionTab | null | undefined,
|
||||
terminals: readonly { handle: string; agentIdentity?: string }[]
|
||||
): AgentSmartKeySet | null {
|
||||
if (tab?.type !== 'terminal' || !isMobileTerminalTabRunningAgent(tab)) {
|
||||
return null
|
||||
}
|
||||
return resolveAgentSmartKeys(
|
||||
resolveMobileTerminalTabOwnedAgentId(
|
||||
tab,
|
||||
getMobileTerminalTabHostAgentIdentity(tab, terminals)
|
||||
),
|
||||
tab.agentStatus
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ const KEY_HEIGHT = 32
|
||||
const KEY_ROW_HEIGHT = 46
|
||||
const KEY_GAP = spacing.sm
|
||||
const KEY_RADIUS = radii.control
|
||||
// The smart group wraps its keys with this much room on each side, inside the same row.
|
||||
const SMART_GROUP_INSET = spacing.xs
|
||||
|
||||
/** Grows each 32 pt key to the row's height and halfway into its neighbours' gaps. */
|
||||
export const TERMINAL_KEY_HIT_SLOP = {
|
||||
@@ -79,6 +81,58 @@ export const terminalDockStyles = themedStyleSheet(() => ({
|
||||
keyPressed: {
|
||||
opacity: feedback.pressedOpacity
|
||||
},
|
||||
// A Shift, Ctrl or Alt latch armed for the next key, and one locked on (the Duo rail's look).
|
||||
// A border on every latch, so arming one doesn't widen it.
|
||||
keyLatch: {
|
||||
borderWidth: 1,
|
||||
borderColor: 'transparent'
|
||||
},
|
||||
keyLatched: {
|
||||
borderColor: colors.textPrimary
|
||||
},
|
||||
keyLocked: {
|
||||
backgroundColor: colors.textPrimary
|
||||
},
|
||||
keyTextLocked: {
|
||||
color: colors.bgBase
|
||||
},
|
||||
smartGroup: {
|
||||
height: KEY_HEIGHT + SMART_GROUP_INSET * 2,
|
||||
flexDirection: 'row',
|
||||
alignItems: 'center',
|
||||
gap: SMART_GROUP_INSET,
|
||||
paddingLeft: spacing.sm,
|
||||
paddingRight: SMART_GROUP_INSET,
|
||||
borderRadius: KEY_RADIUS + SMART_GROUP_INSET,
|
||||
borderWidth: StyleSheet.hairlineWidth,
|
||||
borderColor: colors.composerBorder,
|
||||
backgroundColor: colors.composerSurface
|
||||
},
|
||||
smartDivider: {
|
||||
width: StyleSheet.hairlineWidth,
|
||||
height: KEY_HEIGHT - spacing.sm,
|
||||
backgroundColor: colors.translucentFill
|
||||
},
|
||||
smartKeyStack: {
|
||||
alignItems: 'center'
|
||||
},
|
||||
smartKeyWord: {
|
||||
color: colors.textPrimary,
|
||||
fontSize: typography.metaSize,
|
||||
fontWeight: '600'
|
||||
},
|
||||
smartKeyCombo: {
|
||||
color: colors.textSecondary,
|
||||
fontSize: 10,
|
||||
fontFamily: typography.monoFamily
|
||||
},
|
||||
// The prompt's accept key, in the app's filled primary.
|
||||
smartKeyPrimary: {
|
||||
backgroundColor: colors.surfaceBright
|
||||
},
|
||||
smartKeyPrimaryText: {
|
||||
color: colors.bgBase
|
||||
},
|
||||
ghostKey: {
|
||||
...key,
|
||||
backgroundColor: 'transparent'
|
||||
|
||||
@@ -49,6 +49,10 @@ export function useTerminalDockKeys({ activeHandle, sendInput }: UseTerminalDock
|
||||
return modifiers
|
||||
}
|
||||
|
||||
/** A row key with the held modifiers, or null when none is held or the key takes no modifier. */
|
||||
const chordInput = (key: string): TerminalLiveAccessoryInput | null =>
|
||||
hasStickyModifier(modifiers) ? terminalDockKeyInput(key, modifiers) : null
|
||||
|
||||
/** Sends a special key id (`arrowUp`, `tab`, `f5`…) or a printable character with the held modifiers. */
|
||||
const sendKey = (key: string): void => {
|
||||
const input = terminalDockKeyInput(key, takeModifiers())
|
||||
@@ -75,7 +79,7 @@ export function useTerminalDockKeys({ activeHandle, sendInput }: UseTerminalDock
|
||||
return true
|
||||
}
|
||||
|
||||
return { modifiers, tapModifier, sendKey, interceptTypedCharacter }
|
||||
return { modifiers, tapModifier, takeModifiers, chordInput, sendKey, interceptTypedCharacter }
|
||||
}
|
||||
|
||||
function terminalDockKeyInput(
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
import { useCallback, useEffect, useRef, useState, type RefObject } from 'react'
|
||||
import type {
|
||||
GestureResponderEvent,
|
||||
NativeScrollEvent,
|
||||
NativeSyntheticEvent,
|
||||
ScrollView
|
||||
} from 'react-native'
|
||||
import {
|
||||
sameSmartKeySet,
|
||||
type AgentSmartKeySet
|
||||
} from '../../../../src/shared/terminal/input/agent-smart-keys'
|
||||
|
||||
// The same movement the Duo rail allows before a touch stops counting as a press.
|
||||
const PRESS_MOVE_SLOP = 8
|
||||
// On the page a tap's press is the click after touchend; hold the row until then, or this long.
|
||||
const RELEASE_SETTLE_MS = 300
|
||||
|
||||
/** A web click with no pointer behind it: VoiceOver, Switch Control or a keyboard. */
|
||||
export function isAccessibilityClick(event: GestureResponderEvent): boolean {
|
||||
return event.type === 'click' && 'detail' in event.nativeEvent && event.nativeEvent.detail === 0
|
||||
}
|
||||
|
||||
/** A web click from a finger or mouse; one that never pressed its key landed on a key that moved. */
|
||||
function isPointerClick(event: GestureResponderEvent): boolean {
|
||||
return event.type === 'click' && !isAccessibilityClick(event)
|
||||
}
|
||||
|
||||
/**
|
||||
* Touch rules for the terminal key row: a key fires on release only if the row neither scrolled
|
||||
* nor moved under the finger since it went down, and `shown` holds still from touch-down until that
|
||||
* touch's press has landed. A new `shown` scrolls the row back to its start.
|
||||
*/
|
||||
export function useTerminalKeyRowTouch({
|
||||
scrollRef,
|
||||
latest,
|
||||
cancelAccessoryRepeat
|
||||
}: {
|
||||
scrollRef: RefObject<ScrollView | null>
|
||||
latest: AgentSmartKeySet | null
|
||||
cancelAccessoryRepeat: () => void
|
||||
}) {
|
||||
const [shown, setShown] = useState(latest)
|
||||
const touchRef = useRef({ down: false, moved: false, x: 0, y: 0 })
|
||||
const settleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const pressRevisionRef = useRef(0)
|
||||
const armedRef = useRef(new Map<string, number>())
|
||||
const scrollXRef = useRef(0)
|
||||
const latestRef = useRef(latest)
|
||||
// From touch-down until that touch's press lands (or the settle timer runs out).
|
||||
const holding = () => touchRef.current.down || settleTimerRef.current !== null
|
||||
const show = useCallback(() => {
|
||||
setShown((current) =>
|
||||
sameSmartKeySet(current, latestRef.current) ? current : latestRef.current
|
||||
)
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
latestRef.current = latest
|
||||
if (!holding()) {
|
||||
show()
|
||||
}
|
||||
}, [latest, show])
|
||||
const resetTo = useRef(shown)
|
||||
useEffect(() => {
|
||||
if (resetTo.current !== shown) {
|
||||
resetTo.current = shown
|
||||
scrollRef.current?.scrollTo({ x: 0, animated: false })
|
||||
}
|
||||
}, [scrollRef, shown])
|
||||
|
||||
// Scrolls on the page come only as DOM scroll events; onScrollBeginDrag never fires there.
|
||||
const cancelPresses = useCallback(() => {
|
||||
pressRevisionRef.current += 1
|
||||
cancelAccessoryRepeat()
|
||||
}, [cancelAccessoryRepeat])
|
||||
|
||||
const clearSettleTimer = useCallback(() => {
|
||||
if (settleTimerRef.current) {
|
||||
clearTimeout(settleTimerRef.current)
|
||||
settleTimerRef.current = null
|
||||
}
|
||||
}, [])
|
||||
useEffect(() => clearSettleTimer, [clearSettleTimer])
|
||||
const settle = useCallback(() => {
|
||||
clearSettleTimer()
|
||||
if (!touchRef.current.down) {
|
||||
show()
|
||||
}
|
||||
}, [clearSettleTimer, show])
|
||||
const released = useCallback(() => {
|
||||
touchRef.current.down = false
|
||||
settleTimerRef.current ??= setTimeout(settle, RELEASE_SETTLE_MS)
|
||||
}, [settle])
|
||||
|
||||
return {
|
||||
shown,
|
||||
rowTouchHandlers: {
|
||||
onTouchStart: (event: GestureResponderEvent) => {
|
||||
const { pageX, pageY } = event.nativeEvent
|
||||
touchRef.current = { down: true, moved: false, x: pageX, y: pageY }
|
||||
clearSettleTimer()
|
||||
},
|
||||
onTouchMove: (event: GestureResponderEvent) => {
|
||||
const { pageX, pageY } = event.nativeEvent
|
||||
const start = touchRef.current
|
||||
if (!start.moved && Math.hypot(pageX - start.x, pageY - start.y) > PRESS_MOVE_SLOP) {
|
||||
start.moved = true
|
||||
cancelPresses()
|
||||
}
|
||||
},
|
||||
onTouchEnd: released,
|
||||
onTouchCancel: () => {
|
||||
cancelPresses()
|
||||
released()
|
||||
}
|
||||
},
|
||||
// Only a finger moving the row cancels: the page also reports settling, focus and reset scrolls.
|
||||
onScroll: (event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
const x = event.nativeEvent.contentOffset.x
|
||||
const moved = x !== scrollXRef.current
|
||||
scrollXRef.current = x
|
||||
if (moved && touchRef.current.down) {
|
||||
cancelPresses()
|
||||
}
|
||||
},
|
||||
/** Marks a key as pressed; call from onPressIn. */
|
||||
arm: (id: string): void => {
|
||||
armedRef.current.set(id, pressRevisionRef.current)
|
||||
},
|
||||
/** Whether a key armed by a touch still counts, for a hold that starts before release. */
|
||||
stillArmed: (id: string): boolean => armedRef.current.get(id) === pressRevisionRef.current,
|
||||
/** Runs a key's action on release unless the row moved since it was armed, then lets the row change. */
|
||||
fire: (id: string, event: GestureResponderEvent, action: () => void): void => {
|
||||
const armedAt = armedRef.current.get(id)
|
||||
armedRef.current.delete(id)
|
||||
if (armedAt === undefined ? !isPointerClick(event) : armedAt === pressRevisionRef.current) {
|
||||
action()
|
||||
}
|
||||
settle()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ export type TerminalAccessoryLayout = {
|
||||
orderedBuiltInIds: string[]
|
||||
visibleBuiltInIds: string[]
|
||||
directionPadEnabled?: boolean
|
||||
/** Agent keys at the front of the phone's key row; off unless the user turns it on. */
|
||||
smartRail?: boolean
|
||||
}
|
||||
|
||||
export type TerminalAccessoryLayoutPreference = TerminalAccessoryLayout & {
|
||||
@@ -29,7 +31,8 @@ function defaultPreference(
|
||||
visibleBuiltInIds: directionPadAvailable
|
||||
? ids.filter((id) => !id.startsWith('arrow'))
|
||||
: [...ids],
|
||||
directionPadEnabled: true
|
||||
directionPadEnabled: true,
|
||||
smartRail: false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +91,9 @@ export function getDefaultTerminalAccessoryBuiltInIds(): string[] {
|
||||
export function getDefaultTerminalAccessoryLayout(
|
||||
directionPadAvailable = false
|
||||
): TerminalAccessoryLayout {
|
||||
const { orderedBuiltInIds, visibleBuiltInIds, directionPadEnabled } = defaultPreference(
|
||||
builtInIds(),
|
||||
directionPadAvailable
|
||||
)
|
||||
return { orderedBuiltInIds, visibleBuiltInIds, directionPadEnabled }
|
||||
const { orderedBuiltInIds, visibleBuiltInIds, directionPadEnabled, smartRail } =
|
||||
defaultPreference(builtInIds(), directionPadAvailable)
|
||||
return { orderedBuiltInIds, visibleBuiltInIds, directionPadEnabled, smartRail }
|
||||
}
|
||||
|
||||
export function normalizeTerminalAccessoryLayoutPreference(
|
||||
@@ -110,7 +111,8 @@ export function normalizeTerminalAccessoryLayoutPreference(
|
||||
orderedBuiltInIds: 'orderedBuiltInIds' in value ? value.orderedBuiltInIds : undefined,
|
||||
visibleBuiltInIds: 'visibleBuiltInIds' in value ? value.visibleBuiltInIds : undefined,
|
||||
knownBuiltInIds: 'knownBuiltInIds' in value ? value.knownBuiltInIds : undefined,
|
||||
directionPadEnabled: 'directionPadEnabled' in value ? value.directionPadEnabled : undefined
|
||||
directionPadEnabled: 'directionPadEnabled' in value ? value.directionPadEnabled : undefined,
|
||||
smartRail: 'smartRail' in value ? value.smartRail : undefined
|
||||
}
|
||||
const builtInSet = new Set(currentBuiltInIds)
|
||||
|
||||
@@ -131,6 +133,7 @@ export function normalizeTerminalAccessoryLayoutPreference(
|
||||
return {
|
||||
version: 2,
|
||||
directionPadEnabled: candidate.directionPadEnabled !== false,
|
||||
smartRail: candidate.smartRail === true,
|
||||
orderedBuiltInIds: ordered,
|
||||
visibleBuiltInIds: ordered.filter((id) => visibleSet.has(id))
|
||||
}
|
||||
@@ -153,6 +156,7 @@ export function normalizeTerminalAccessoryLayoutPreference(
|
||||
return {
|
||||
version: 2,
|
||||
directionPadEnabled: candidate.directionPadEnabled !== false,
|
||||
smartRail: candidate.smartRail === true,
|
||||
orderedBuiltInIds: [...currentBuiltInIds],
|
||||
visibleBuiltInIds: currentBuiltInIds.filter((id) => visibleSet.has(id))
|
||||
}
|
||||
@@ -174,6 +178,7 @@ export function createTerminalAccessoryLayoutPreference(
|
||||
return {
|
||||
version: 2,
|
||||
directionPadEnabled: layout.directionPadEnabled !== false,
|
||||
smartRail: layout.smartRail === true,
|
||||
orderedBuiltInIds: ordered,
|
||||
visibleBuiltInIds: ordered.filter((id) => visibleSet.has(id))
|
||||
}
|
||||
@@ -189,6 +194,7 @@ export function setTerminalAccessoryBuiltInVisible(
|
||||
if (!new Set(currentBuiltInIds).has(id)) {
|
||||
return {
|
||||
directionPadEnabled: preference.directionPadEnabled,
|
||||
smartRail: preference.smartRail,
|
||||
orderedBuiltInIds: preference.orderedBuiltInIds,
|
||||
visibleBuiltInIds: preference.visibleBuiltInIds
|
||||
}
|
||||
@@ -201,6 +207,7 @@ export function setTerminalAccessoryBuiltInVisible(
|
||||
}
|
||||
return {
|
||||
directionPadEnabled: preference.directionPadEnabled,
|
||||
smartRail: preference.smartRail,
|
||||
orderedBuiltInIds: preference.orderedBuiltInIds,
|
||||
visibleBuiltInIds: preference.orderedBuiltInIds.filter((builtInId) => visibleSet.has(builtInId))
|
||||
}
|
||||
@@ -217,6 +224,7 @@ export function reorderTerminalAccessoryBuiltInIds(
|
||||
)
|
||||
return {
|
||||
directionPadEnabled: preference.directionPadEnabled,
|
||||
smartRail: preference.smartRail,
|
||||
orderedBuiltInIds: preference.orderedBuiltInIds,
|
||||
visibleBuiltInIds: preference.visibleBuiltInIds
|
||||
}
|
||||
@@ -236,22 +244,24 @@ export function getVisibleTerminalAccessoryKeys(
|
||||
})
|
||||
}
|
||||
|
||||
export async function loadTerminalAccessoryLayout(
|
||||
// Throws only when the store can't be read; a malformed value reads as the defaults.
|
||||
async function readTerminalAccessoryLayout(
|
||||
directionPadAvailable: boolean
|
||||
): Promise<TerminalAccessoryLayoutPreference> {
|
||||
const raw = await AsyncStorage.getItem(TERMINAL_ACCESSORY_LAYOUT_STORAGE_KEY)
|
||||
let stored: unknown = null
|
||||
try {
|
||||
stored = raw ? JSON.parse(raw) : null
|
||||
} catch {}
|
||||
return normalizeTerminalAccessoryLayoutPreference(stored, builtInIds(), directionPadAvailable)
|
||||
}
|
||||
|
||||
export function loadTerminalAccessoryLayout(
|
||||
directionPadAvailable = false
|
||||
): Promise<TerminalAccessoryLayoutPreference> {
|
||||
try {
|
||||
const raw = await AsyncStorage.getItem(TERMINAL_ACCESSORY_LAYOUT_STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return defaultPreference(builtInIds(), directionPadAvailable)
|
||||
}
|
||||
return normalizeTerminalAccessoryLayoutPreference(
|
||||
JSON.parse(raw),
|
||||
builtInIds(),
|
||||
directionPadAvailable
|
||||
)
|
||||
} catch {
|
||||
return defaultPreference(builtInIds(), directionPadAvailable)
|
||||
}
|
||||
return readTerminalAccessoryLayout(directionPadAvailable).catch(() =>
|
||||
defaultPreference(builtInIds(), directionPadAvailable)
|
||||
)
|
||||
}
|
||||
|
||||
export async function saveTerminalAccessoryLayout(layout: TerminalAccessoryLayout): Promise<void> {
|
||||
@@ -259,3 +269,20 @@ export async function saveTerminalAccessoryLayout(layout: TerminalAccessoryLayou
|
||||
const value = JSON.stringify(preference)
|
||||
await persistMirrored(TERMINAL_ACCESSORY_LAYOUT_STORAGE_KEY, value)
|
||||
}
|
||||
|
||||
// Serialize read-modify-write so quick toggles land in order.
|
||||
let layoutWriteTurn: Promise<unknown> = Promise.resolve()
|
||||
|
||||
/** Turns the Smart rail on or off, keeping the rest of the stored layout. */
|
||||
export function saveTerminalSmartRail(
|
||||
enabled: boolean,
|
||||
directionPadAvailable = false
|
||||
): Promise<void> {
|
||||
const run = layoutWriteTurn.then(async () => {
|
||||
// A failed read must not save defaults over the user's layout.
|
||||
const layout = await readTerminalAccessoryLayout(directionPadAvailable)
|
||||
await saveTerminalAccessoryLayout({ ...layout, smartRail: enabled })
|
||||
})
|
||||
layoutWriteTurn = run.catch(() => {})
|
||||
return run
|
||||
}
|
||||
|
||||
@@ -5,3 +5,7 @@ Handle a whole `check` batch before the next `check`.
|
||||
Groups (`@all`, `@idle`, `@codex`, ...) reach the live workers of your Run;
|
||||
`@worktree:<id>` also reaches coordinators in that workspace. Use groups only
|
||||
for deliberate fan-out.
|
||||
|
||||
To reach an agent on a paired server, use `send --on <server>`; a reply to mail
|
||||
from another server needs no flag. See
|
||||
[Placement and remote execution](placement-and-remote.md).
|
||||
|
||||
@@ -35,3 +35,24 @@ workspace, and the start output names the workspace it created.
|
||||
|
||||
After start, address a remote worker only by Dispatch ID, never by a terminal
|
||||
handle.
|
||||
|
||||
## Agents on another server
|
||||
|
||||
To message an agent that already runs on a paired server, send with `--on`,
|
||||
using the same server names as `worker-start --on`:
|
||||
|
||||
```bash
|
||||
ORCA orchestration send --on <server> --to <term_…|orca_session_id:…> --subject "<text>" --body "<text>"
|
||||
```
|
||||
|
||||
Your own Orca carries the mail and keeps the conversation. Replies come back to
|
||||
your own `check`, and they wake you like local mail. The other agent answers
|
||||
with a plain `reply --id <msg_id> --body <text>`; no flag is needed on either
|
||||
side. Mail from another server names its sender as `<sender> on <server name>`.
|
||||
|
||||
`--environment <server>` runs one command on that server and delivers nothing back
|
||||
to you, so an agent never mails with it. Your mailbox stays on your own Orca:
|
||||
`check` takes no `--environment`. Read-only commands such as `inbox` or
|
||||
`worker-list` with `--environment` show that server's records. A server whose Orca
|
||||
is too old answers `server_mail_unsupported` and nothing is sent. Pair servers
|
||||
with `orca pair` or in Settings.
|
||||
|
||||
@@ -4101,6 +4101,10 @@ const ORCHESTRATION_MESSAGING_AND_GATES_REFERENCE_MARKDOWN = [
|
||||
"`@worktree:<id>` also reaches coordinators in that workspace. Use groups only",
|
||||
"for deliberate fan-out.",
|
||||
"",
|
||||
"To reach an agent on a paired server, use `send --on <server>`; a reply to mail",
|
||||
"from another server needs no flag. See",
|
||||
"[Placement and remote execution](placement-and-remote.md).",
|
||||
"",
|
||||
].join('\n')
|
||||
|
||||
// oxfmt-ignore
|
||||
@@ -4143,6 +4147,27 @@ const ORCHESTRATION_PLACEMENT_AND_REMOTE_REFERENCE_MARKDOWN = [
|
||||
"After start, address a remote worker only by Dispatch ID, never by a terminal",
|
||||
"handle.",
|
||||
"",
|
||||
"## Agents on another server",
|
||||
"",
|
||||
"To message an agent that already runs on a paired server, send with `--on`,",
|
||||
"using the same server names as `worker-start --on`:",
|
||||
"",
|
||||
"```bash",
|
||||
"ORCA orchestration send --on <server> --to <term_…|orca_session_id:…> --subject \"<text>\" --body \"<text>\"",
|
||||
"```",
|
||||
"",
|
||||
"Your own Orca carries the mail and keeps the conversation. Replies come back to",
|
||||
"your own `check`, and they wake you like local mail. The other agent answers",
|
||||
"with a plain `reply --id <msg_id> --body <text>`; no flag is needed on either",
|
||||
"side. Mail from another server names its sender as `<sender> on <server name>`.",
|
||||
"",
|
||||
"`--environment <server>` runs one command on that server and delivers nothing back",
|
||||
"to you, so an agent never mails with it. Your mailbox stays on your own Orca:",
|
||||
"`check` takes no `--environment`. Read-only commands such as `inbox` or",
|
||||
"`worker-list` with `--environment` show that server's records. A server whose Orca",
|
||||
"is too old answers `server_mail_unsupported` and nothing is sent. Pair servers",
|
||||
"with `orca pair` or in Settings.",
|
||||
"",
|
||||
].join('\n')
|
||||
|
||||
// oxfmt-ignore
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type * as RuntimeClientModule from '../../runtime-client'
|
||||
import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route'
|
||||
|
||||
const { callerShow } = vi.hoisted(() => ({ callerShow: vi.fn() }))
|
||||
vi.mock('../../runtime-client', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof RuntimeClientModule>()
|
||||
return {
|
||||
...actual,
|
||||
RuntimeClient: class {
|
||||
call = callerShow
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
function ctx(command: string[], flags: [string, string | boolean][]) {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads.
|
||||
return {
|
||||
flags: new Map(flags),
|
||||
client: { isRemote: true },
|
||||
cwd: '/',
|
||||
json: false,
|
||||
rawArgs: [...command, ...flags.flatMap(([name, value]) => [`--${name}`, String(value)])]
|
||||
} as unknown as Parameters<typeof refuseAgentServerRoute>[1]
|
||||
}
|
||||
|
||||
describe('an agent pointing mail at another server', () => {
|
||||
beforeEach(() => {
|
||||
vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', 'launch-token')
|
||||
vi.stubEnv('ORCA_AGENT_SESSION_ID', '')
|
||||
vi.stubEnv('ORCA_CLI_COMMAND', 'orca')
|
||||
callerShow.mockResolvedValue({ result: { caller: null, terminal: true } })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
callerShow.mockReset()
|
||||
})
|
||||
|
||||
it('is refused with the --on command to run instead', async () => {
|
||||
await expect(
|
||||
refuseAgentServerRoute(
|
||||
'send',
|
||||
ctx(
|
||||
['orchestration', 'send'],
|
||||
[
|
||||
['environment', 'devB'],
|
||||
['to', 'term_b'],
|
||||
['subject', 'hi']
|
||||
]
|
||||
)
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
code: 'agent_server_route_refused',
|
||||
message:
|
||||
'send with --environment devB runs on devB and nothing comes back to you. To message an agent on devB, use: orca orchestration send --on devB --to term_b --subject hi'
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a check against another server: the mailbox is local', async () => {
|
||||
await expect(
|
||||
refuseAgentServerRoute('check', ctx(['orchestration', 'check'], [['environment', 'devB']]))
|
||||
).rejects.toMatchObject({
|
||||
code: 'mailbox_is_local',
|
||||
message:
|
||||
'Your mailbox is on this Orca; replies from devB arrive here. Drop --environment devB.'
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves a person in a shell running the command on that server', async () => {
|
||||
vi.stubEnv('ORCA_AGENT_LAUNCH_TOKEN', '')
|
||||
await expect(
|
||||
refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']]))
|
||||
).resolves.toBeUndefined()
|
||||
expect(callerShow).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('leaves a launch its own Orca does not verify running on that server', async () => {
|
||||
callerShow.mockResolvedValue({ result: { caller: null, terminal: false } })
|
||||
await expect(
|
||||
refuseAgentServerRoute('send', ctx(['orchestration', 'send'], [['environment', 'devB']]))
|
||||
).resolves.toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('send --on from an older Orca', () => {
|
||||
it('is refused before anything is sent', async () => {
|
||||
const call = vi
|
||||
.fn()
|
||||
.mockResolvedValue({ result: { capabilities: ['orchestration.contract.v1'] } })
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: a handler context with only the fields this function reads.
|
||||
const context = {
|
||||
flags: new Map([['on', 'devB']]),
|
||||
client: { call },
|
||||
cwd: '/',
|
||||
json: false
|
||||
} as unknown as Parameters<typeof requirePeerMailCarrier>[0]
|
||||
|
||||
await expect(requirePeerMailCarrier(context)).rejects.toMatchObject({
|
||||
code: 'server_mail_unsupported'
|
||||
})
|
||||
expect(call).toHaveBeenCalledTimes(1)
|
||||
expect(call).toHaveBeenCalledWith('status.get')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { HandlerContext } from '../../dispatch'
|
||||
import { RuntimeClient, RuntimeClientError } from '../../runtime-client'
|
||||
import { readInjectedAgentSessionId } from '../../../shared/agent-session/lifecycle/agent-session-caller-env'
|
||||
import type { OrchestrationCallerShowResult } from '../../../shared/orchestration/orchestration-caller-status'
|
||||
import { renderOrchestrationArgv } from './agent-view'
|
||||
import type { RuntimeStatus } from '../../../shared/runtime-types'
|
||||
import { ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY } from '../../../shared/orchestration/orchestration-runtime-capabilities'
|
||||
|
||||
type AgentServerRoutedCommand = 'send' | 'worker-start' | 'check'
|
||||
|
||||
/** The server a remote client was pointed at, as the caller spelled it. */
|
||||
function serverSelector(
|
||||
flags: HandlerContext['flags']
|
||||
): { name: string; route: string } | undefined {
|
||||
const explicit = flags.get('environment')
|
||||
if (typeof explicit === 'string') {
|
||||
return { name: explicit, route: `--environment ${explicit}` }
|
||||
}
|
||||
const inherited = process.env.ORCA_ENVIRONMENT?.trim()
|
||||
return inherited ? { name: inherited, route: `ORCA_ENVIRONMENT=${inherited}` } : undefined
|
||||
}
|
||||
|
||||
/** Only an agent its own Orca verifies counts; a person's shell keeps --environment = run it there. */
|
||||
async function isOrcaVerifiedAgent(): Promise<boolean> {
|
||||
if (!readInjectedAgentSessionId() && !process.env.ORCA_AGENT_LAUNCH_TOKEN?.trim()) {
|
||||
return false
|
||||
}
|
||||
try {
|
||||
const local = new RuntimeClient(undefined, 10_000, null, null)
|
||||
const { result } = await local.call<OrchestrationCallerShowResult>('orchestration.callerShow')
|
||||
return result.caller !== null || result.terminal === true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/** The same command with the server moved from --environment to --on. */
|
||||
function withOn(rawArgs: readonly string[] | undefined, server: string): string {
|
||||
const args = rawArgs ?? []
|
||||
const kept: string[] = []
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const arg = args[index]!
|
||||
const [name] = arg.split('=', 1)
|
||||
if (name === '--environment') {
|
||||
if (!arg.includes('=')) {
|
||||
index += 1
|
||||
}
|
||||
continue
|
||||
}
|
||||
kept.push(arg)
|
||||
}
|
||||
const at = kept.findIndex((arg) => arg === 'send' || arg === 'worker-start')
|
||||
kept.splice(at + 1, 0, '--on', server)
|
||||
return renderOrchestrationArgv(kept) ?? ''
|
||||
}
|
||||
|
||||
/** An agent's mail and workers live on its own Orca; pointing them at another server reaches nobody. */
|
||||
export async function refuseAgentServerRoute(
|
||||
command: AgentServerRoutedCommand,
|
||||
ctx: HandlerContext
|
||||
): Promise<void> {
|
||||
if (!ctx.client.isRemote || ctx.flags.has('on')) {
|
||||
return
|
||||
}
|
||||
const server = serverSelector(ctx.flags)
|
||||
if (!server || !(await isOrcaVerifiedAgent())) {
|
||||
return
|
||||
}
|
||||
const { name, route } = server
|
||||
if (command === 'check') {
|
||||
throw new RuntimeClientError(
|
||||
'mailbox_is_local',
|
||||
`Your mailbox is on this Orca; replies from ${name} arrive here. Drop ${route}.`
|
||||
)
|
||||
}
|
||||
const verb = command === 'send' ? 'message an agent' : 'start a worker'
|
||||
throw new RuntimeClientError(
|
||||
'agent_server_route_refused',
|
||||
`${command} with ${route} runs on ${name} and nothing comes back to you. To ${verb} on ${name}, use: ${withOn(ctx.rawArgs, name)}`
|
||||
)
|
||||
}
|
||||
|
||||
/** An older Orca would drop --on and send the mail to an agent here, so it must carry mail between servers first. */
|
||||
export async function requirePeerMailCarrier(ctx: HandlerContext): Promise<void> {
|
||||
if (!ctx.flags.has('on')) {
|
||||
return
|
||||
}
|
||||
const { result } = await ctx.client.call<RuntimeStatus>('status.get')
|
||||
if (!result.capabilities?.includes(ORCHESTRATION_PEER_MAIL_RUNTIME_CAPABILITY)) {
|
||||
throw new RuntimeClientError(
|
||||
'server_mail_unsupported',
|
||||
'The Orca running here is too old to carry mail to another server. Update or restart Orca here, then send again. Nothing was sent.'
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CommandHandler } from '../../dispatch'
|
||||
import { refuseAgentServerRoute } from './agent-server-route'
|
||||
import { printResult } from '../../format'
|
||||
import { withReceiptNext } from './receipt-next-text'
|
||||
import { printOrchestrationResult } from './agent-view'
|
||||
@@ -32,7 +33,9 @@ type CheckResult = {
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_CHECK_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration check': async ({ flags, client, cwd, json }) => {
|
||||
'orchestration check': async (ctx) => {
|
||||
const { flags, client, cwd, json } = ctx
|
||||
await refuseAgentServerRoute('check', ctx)
|
||||
const wait = flags.has('wait')
|
||||
const peek = flags.has('peek')
|
||||
// Older runtimes ignore peek, making --unread --peek destructive.
|
||||
|
||||
@@ -11,13 +11,16 @@ import {
|
||||
type OrchestrationMessageSummary as MessageSummary
|
||||
} from '../../../shared/orchestration/mailbox/orchestration-check-output'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { requirePeerMailCarrier } from './agent-server-route'
|
||||
import { resolveOrchestrationTerminalHandle } from './terminal-identity'
|
||||
import { withReceiptNext } from './receipt-next-text'
|
||||
import { printOrchestrationResult } from './agent-view'
|
||||
import { formatMessageViewText, toMessageView, type MessageView } from './message-agent-views'
|
||||
|
||||
export const ORCHESTRATION_INBOX_HANDLERS: Record<string, CommandHandler> = {
|
||||
'orchestration reply': async ({ flags, client, cwd, json }) => {
|
||||
'orchestration reply': async (ctx) => {
|
||||
const { flags, client, cwd, json } = ctx
|
||||
await requirePeerMailCarrier(ctx)
|
||||
const from = await resolveOrchestrationTerminalHandle(flags, cwd, client, 'from')
|
||||
const result = await callOrchestrationMutation<{
|
||||
message: { id: string }
|
||||
@@ -27,6 +30,7 @@ export const ORCHESTRATION_INBOX_HANDLERS: Record<string, CommandHandler> = {
|
||||
id: getRequiredStringFlag(flags, 'id'),
|
||||
body: getRequiredStringFlag(flags, 'body'),
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
on: getOptionalStringFlag(flags, 'on'),
|
||||
from
|
||||
})
|
||||
if (!flags.has('full')) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { requireWorkerDoneSettlement } from '../orchestration-worker-settlement'
|
||||
import { getOptionalStructuredMessagePayload } from './message-payload'
|
||||
import { callOrchestrationMutation } from './mutation-request'
|
||||
import { isDevCliInvocation } from './runtime-compatibility'
|
||||
import { refuseAgentServerRoute, requirePeerMailCarrier } from './agent-server-route'
|
||||
import {
|
||||
resolveOrchestrationTerminalHandle,
|
||||
throwNoActiveSenderTerminal
|
||||
@@ -70,7 +71,10 @@ function rejectLifecycleGroupRecipient(type: string | undefined, to: string): vo
|
||||
}
|
||||
|
||||
export const ORCHESTRATION_SEND_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration send': async ({ flags, client, cwd, json }) => {
|
||||
'orchestration send': async (ctx) => {
|
||||
const { flags, client, cwd, json } = ctx
|
||||
await refuseAgentServerRoute('send', ctx)
|
||||
await requirePeerMailCarrier(ctx)
|
||||
const to = getOptionalStringFlag(flags, 'to')
|
||||
const type = getOptionalStringFlag(flags, 'type')
|
||||
if (to) {
|
||||
@@ -99,6 +103,7 @@ export const ORCHESTRATION_SEND_HANDLER: Record<string, CommandHandler> = {
|
||||
from,
|
||||
to,
|
||||
run: getOptionalStringFlag(flags, 'run'),
|
||||
on: getOptionalStringFlag(flags, 'on'),
|
||||
subject: getRequiredStringFlag(flags, 'subject'),
|
||||
body: getOptionalStringFlag(flags, 'body'),
|
||||
type,
|
||||
|
||||
@@ -19,9 +19,12 @@ import {
|
||||
import { explainOlderRuntimeRunRequired } from './older-runtime-run-binding'
|
||||
import { withResolvedNextCommands } from '../../orchestration-mutation-recovery'
|
||||
import { readTextOrFileFlag } from '../../command-body-input'
|
||||
import { refuseAgentServerRoute } from './agent-server-route'
|
||||
|
||||
export const ORCHESTRATION_WORKER_LAUNCH_HANDLER: Record<string, CommandHandler> = {
|
||||
'orchestration worker-start': async ({ flags, client, cwd, json }) => {
|
||||
'orchestration worker-start': async (ctx) => {
|
||||
const { flags, client, cwd, json } = ctx
|
||||
await refuseAgentServerRoute('worker-start', ctx)
|
||||
const terminal = getPresentStringFlag(flags, 'terminal')
|
||||
const model = getOptionalStringFlag(flags, 'model')
|
||||
const effort = getOptionalStringFlag(flags, 'effort')
|
||||
|
||||
@@ -103,6 +103,29 @@ describe('--environment local and workspace addresses', () => {
|
||||
}
|
||||
})
|
||||
|
||||
it('runs worker-start --on on this Orca despite an inherited ORCA_ENVIRONMENT', async () => {
|
||||
const args = [
|
||||
'orchestration',
|
||||
'worker-start',
|
||||
'--on',
|
||||
'build-box',
|
||||
'--spec',
|
||||
'Go',
|
||||
'--agent',
|
||||
'claude'
|
||||
]
|
||||
vi.stubEnv('ORCA_ENVIRONMENT', 'srv-b')
|
||||
runtimeClientConstructorMock.mockClear()
|
||||
listEnvironmentsMock.mockReturnValue(SAVED)
|
||||
callMock.mockRejectedValue(new RuntimeClientError('runtime_unavailable', 'stop here'))
|
||||
await run([...args, '--json'])
|
||||
expect(runtimeClientConstructorMock).toHaveBeenCalled()
|
||||
expect(
|
||||
runtimeClientConstructorMock.mock.calls.every(([, environment]) => environment === null)
|
||||
).toBe(true)
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
it('refuses current against another environment with an inspection command', async () => {
|
||||
listEnvironmentsMock.mockReturnValue(SAVED)
|
||||
const { exitCode, output } = await run([
|
||||
|
||||
+27
-1
@@ -105,7 +105,20 @@ export async function main(
|
||||
refuseConflictingSessionCallerFlags(commandSpec, parsed.flags)
|
||||
await refuseLocalManagementSelector(parsed.commandPath, parsed.flags)
|
||||
const RuntimeClientClass = await loadRuntimeClientClass()
|
||||
const ignoreRemoteSelection = ignoresRemoteSelection(parsed.commandPath)
|
||||
// `--on` runs on the caller's own Orca, which reaches that server; an inherited selection never reroutes it.
|
||||
const onCallersOrca = runsOnCallersOrca(parsed.commandPath, parsed.flags)
|
||||
if (
|
||||
onCallersOrca &&
|
||||
(parsed.flags.has('pairing-code') ||
|
||||
(parsed.flags.has('environment') &&
|
||||
!isLocalEnvironmentSelector(parsed.flags.get('environment'))))
|
||||
) {
|
||||
throw new RuntimeClientError(
|
||||
'invalid_argument',
|
||||
'--on already names the server; drop --environment. Your own Orca reaches it.'
|
||||
)
|
||||
}
|
||||
const ignoreRemoteSelection = onCallersOrca || ignoresRemoteSelection(parsed.commandPath)
|
||||
const pairingCode = ignoreRemoteSelection ? null : parsed.flags.get('pairing-code')
|
||||
const environmentSelector = ignoreRemoteSelection ? null : parsed.flags.get('environment')
|
||||
// An explicit local route suppresses ambient ORCA_ENVIRONMENT and pairing codes.
|
||||
@@ -192,6 +205,19 @@ export async function main(
|
||||
}
|
||||
}
|
||||
|
||||
const ON_CALLERS_ORCA_COMMANDS: ReadonlySet<string> = new Set(['send', 'reply', 'worker-start'])
|
||||
|
||||
function runsOnCallersOrca(
|
||||
commandPath: readonly string[],
|
||||
flags: ReadonlyMap<string, string | boolean>
|
||||
): boolean {
|
||||
return (
|
||||
commandPath[0] === 'orchestration' &&
|
||||
ON_CALLERS_ORCA_COMMANDS.has(commandPath[1] ?? '') &&
|
||||
flags.has('on')
|
||||
)
|
||||
}
|
||||
|
||||
async function runClaudeTeams(argv: string[], cwd: string): Promise<void> {
|
||||
try {
|
||||
// Forward Claude Code arguments verbatim so new flags work without Orca changes.
|
||||
|
||||
@@ -38,10 +38,7 @@ import {
|
||||
ORCHESTRATION_CONTRACT_VERSION
|
||||
} from '../../shared/orchestration/orchestration-runtime-capabilities'
|
||||
import { RemoteRuntimeCompatGate } from './remote-runtime-compat-gate'
|
||||
import {
|
||||
createAgentLaunchCallerEvidence,
|
||||
createOrchestrationCompatibilityEnvelope
|
||||
} from './orchestration-compatibility-envelope'
|
||||
import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope'
|
||||
import { getTimeoutMsParam, isWaitingCheck } from './runtime-request-timeout'
|
||||
import {
|
||||
isWorkerStartTimeoutWithinTimerLimit,
|
||||
@@ -56,7 +53,6 @@ import {
|
||||
|
||||
const LONG_POLL_CLIENT_GRACE_MS = 10_000
|
||||
// The host records the launched agent in the caller's chat; older hosts ignore the evidence.
|
||||
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
|
||||
|
||||
const loadWebSocketTransport = async () => await import('./websocket-transport.js')
|
||||
|
||||
@@ -68,10 +64,7 @@ export class RuntimeClient {
|
||||
private readonly originalArgs: readonly string[] | undefined
|
||||
private readonly remoteCompat: RemoteRuntimeCompatGate
|
||||
private orchestrationContractCheck: Promise<void> | null = null
|
||||
private readonly orchestrationCompatibility = createOrchestrationCompatibilityEnvelope(
|
||||
process.env
|
||||
)
|
||||
private readonly agentLaunchCaller = createAgentLaunchCallerEvidence(process.env)
|
||||
private readonly requestEvidence = new OrchestrationRequestEvidence(process.env)
|
||||
private readonly runtimeSourceFence: RuntimeSourceFence
|
||||
|
||||
// Browser session cold starts can take 15–30 seconds; allow time for initialization.
|
||||
@@ -139,15 +132,11 @@ export class RuntimeClient {
|
||||
: error
|
||||
}
|
||||
}
|
||||
const compatibilityEnvelope = method.startsWith('orchestration.')
|
||||
? {
|
||||
...this.orchestrationCompatibility,
|
||||
compatibilityInvocationId:
|
||||
orchestrationRequestId ?? this.orchestrationCompatibility.compatibilityInvocationId
|
||||
}
|
||||
: AGENT_LAUNCH_METHODS.has(method) && !this.remote && this.agentLaunchCaller
|
||||
? { orchestrationCompatibilityEvidence: this.agentLaunchCaller }
|
||||
: {}
|
||||
const compatibilityEnvelope = this.requestEvidence.envelopeFor(method, {
|
||||
remote: this.remote !== null,
|
||||
mutation: orchestrationMutation,
|
||||
requestId: orchestrationRequestId
|
||||
})
|
||||
const envelope = {
|
||||
orchestrationCapability: options?.orchestrationCapability,
|
||||
orchestrationContractVersion: method.startsWith('orchestration.')
|
||||
|
||||
@@ -26,3 +26,40 @@ export function createAgentLaunchCallerEvidence(
|
||||
}
|
||||
return { agentSessionId }
|
||||
}
|
||||
|
||||
const AGENT_LAUNCH_METHODS: ReadonlySet<string> = new Set(['agent.launch', 'agent.launchReplay'])
|
||||
|
||||
/** The caller evidence one request carries, read from this process's environment once. */
|
||||
export class OrchestrationRequestEvidence {
|
||||
private readonly orchestration: RuntimeOrchestrationEnvelope
|
||||
// A chat's session id means nothing on another server, so reads there go like a shell's.
|
||||
private readonly remoteRead: RuntimeOrchestrationEnvelope
|
||||
private readonly agentLaunchCaller: RuntimeOrchestrationEnvelope['orchestrationCompatibilityEvidence']
|
||||
|
||||
constructor(env: NodeJS.ProcessEnv) {
|
||||
this.orchestration = createOrchestrationCompatibilityEnvelope(env)
|
||||
const { agentSessionId: _session, ...shell } =
|
||||
this.orchestration.orchestrationCompatibilityEvidence ?? {}
|
||||
this.remoteRead = {
|
||||
...this.orchestration,
|
||||
orchestrationCompatibilityEvidence: Object.keys(shell).length > 0 ? shell : undefined
|
||||
}
|
||||
this.agentLaunchCaller = createAgentLaunchCallerEvidence(env)
|
||||
}
|
||||
|
||||
envelopeFor(
|
||||
method: string,
|
||||
request: { remote: boolean; mutation: boolean; requestId: string | undefined }
|
||||
): RuntimeOrchestrationEnvelope {
|
||||
if (method.startsWith('orchestration.')) {
|
||||
const base = request.remote && !request.mutation ? this.remoteRead : this.orchestration
|
||||
return {
|
||||
...base,
|
||||
compatibilityInvocationId: request.requestId ?? base.compatibilityInvocationId
|
||||
}
|
||||
}
|
||||
return AGENT_LAUNCH_METHODS.has(method) && !request.remote && this.agentLaunchCaller
|
||||
? { orchestrationCompatibilityEvidence: this.agentLaunchCaller }
|
||||
: {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { OrchestrationRequestEvidence } from './orchestration-compatibility-envelope'
|
||||
|
||||
const CHAT = { ORCA_AGENT_SESSION_ID: '11111111-1111-4111-8111-111111111111' }
|
||||
|
||||
describe('caller evidence on requests to another server', () => {
|
||||
it('sends a chat read there like a shell, with no session id', () => {
|
||||
const evidence = new OrchestrationRequestEvidence(CHAT)
|
||||
expect(
|
||||
evidence.envelopeFor('orchestration.inbox', {
|
||||
remote: true,
|
||||
mutation: false,
|
||||
requestId: undefined
|
||||
}).orchestrationCompatibilityEvidence
|
||||
).toBeUndefined()
|
||||
})
|
||||
|
||||
it('keeps the session id on writes there, so that server still refuses them', () => {
|
||||
const evidence = new OrchestrationRequestEvidence(CHAT)
|
||||
expect(
|
||||
evidence.envelopeFor('orchestration.taskCreate', {
|
||||
remote: true,
|
||||
mutation: true,
|
||||
requestId: 'request_1'
|
||||
}).orchestrationCompatibilityEvidence
|
||||
).toEqual({ agentSessionId: '11111111-1111-4111-8111-111111111111' })
|
||||
})
|
||||
})
|
||||
@@ -49,10 +49,11 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
|
||||
path: ['orchestration', 'send'],
|
||||
summary: 'Send an inter-agent message',
|
||||
usage:
|
||||
'orca orchestration send --subject <text> [--to <run:id|dispatch:id|legacy_handle>] [--run <run_id>] [--from <handle>] [--body <text>] [--type <type>] [--priority <level>] [--thread-id <id>] [--payload <json>] [--task-id <id>] [--dispatch-id <id>] [--outcome <succeeded|failed>] [--files-modified <csv>] [--report-path <path>] [--phase <text>] [--retry-request <id>] [--json]',
|
||||
'orca orchestration send --subject <text> [--to <run:id|dispatch:id|legacy_handle>] [--on <server>] [--run <run_id>] [--from <handle>] [--body <text>] [--type <type>] [--priority <level>] [--thread-id <id>] [--payload <json>] [--task-id <id>] [--dispatch-id <id>] [--outcome <succeeded|failed>] [--files-modified <csv>] [--report-path <path>] [--phase <text>] [--retry-request <id>] [--json]',
|
||||
allowedFlags: [
|
||||
...GLOBAL_FLAGS,
|
||||
'to',
|
||||
'on',
|
||||
'run',
|
||||
'from',
|
||||
'subject',
|
||||
@@ -82,7 +83,8 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
|
||||
'From a worker, an omitted recipient defaults to its coordinator, also after it finished; mail sent after finishing, worker_done included, leaves the finished task unchanged.',
|
||||
'Use --to dispatch:<id> for attempt-specific coordinator guidance; Orca durably relays it to a connected worker server.',
|
||||
'A worker_done with the active task/dispatch IDs completes that task only from the dispatched pane. When stable pane identity is unavailable, the sender handle must exactly match the dispatch assignee; injected preambles include the correct --from value.',
|
||||
'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.'
|
||||
'Prefer --task-id/--dispatch-id/etc. over raw --payload JSON in worker commands; PowerShell strips JSON quotes easily.',
|
||||
'--on <server> mails a terminal or chat agent on a paired server (--to term_… or orca_session_id:…). Your own Orca carries it, and replies come back to your own check. From an agent, --environment runs the command on that server and delivers no mail.'
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -126,8 +128,12 @@ export const ORCHESTRATION_COMMAND_SPECS: CommandSpec[] = [
|
||||
summary: 'Reply to a message',
|
||||
usage:
|
||||
'orca orchestration reply --id <msg_id> --body <text> [--run <run_id>] [--from <handle>] [--retry-request <id>] [--json]',
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'retry-request'],
|
||||
identityFlagRoles: { from: 'caller' }
|
||||
// --on is accepted only to refuse it with the fix; a reply finds its server by itself.
|
||||
allowedFlags: [...GLOBAL_FLAGS, 'id', 'body', 'run', 'from', 'on', 'retry-request'],
|
||||
identityFlagRoles: { from: 'caller' },
|
||||
notes: [
|
||||
'A reply to mail from an agent on another server goes back to that server by itself; no flag is needed.'
|
||||
]
|
||||
},
|
||||
{
|
||||
path: ['orchestration', 'inbox'],
|
||||
|
||||
@@ -19,7 +19,7 @@ import type { AcpSubagentUpdate } from '../acp-dialects/acp-dialect'
|
||||
type KnownSubagent = {
|
||||
/** Pin replies to the spawning turn. */
|
||||
placement: ProviderTimelineJoin
|
||||
reply?: string
|
||||
replyDigest?: string
|
||||
/** Preserve the first terminal state; only completed runs can publish replies. */
|
||||
ended?: NativeChatSubagentState
|
||||
}
|
||||
@@ -88,7 +88,7 @@ export class AcpSubagents {
|
||||
this.known.set(update.id, subagent)
|
||||
if (update.restart && subagent.ended !== undefined) {
|
||||
subagent.ended = undefined
|
||||
subagent.reply = undefined
|
||||
subagent.replyDigest = undefined
|
||||
}
|
||||
const ending = update.state !== undefined && acpSubagentOutcome(update.state) !== undefined
|
||||
// Late live reports must not resurrect an ended run after the host retires its record.
|
||||
@@ -106,10 +106,11 @@ export class AcpSubagents {
|
||||
}
|
||||
|
||||
private reply(id: string, subagent: KnownSubagent, text: string): ProviderTimelineEvent[] {
|
||||
if (subagent.reply === text) {
|
||||
const digest = createHash('sha256').update(text, 'utf16le').digest('hex')
|
||||
if (subagent.replyDigest === digest) {
|
||||
return []
|
||||
}
|
||||
subagent.reply = text
|
||||
subagent.replyDigest = digest
|
||||
return [
|
||||
{
|
||||
type: 'item.update',
|
||||
|
||||
@@ -265,6 +265,7 @@ export abstract class AgentHookServerCleanup extends AgentHookServerAuthorityFen
|
||||
// A replacement remote process may reuse the pane; discard the lost owner's children.
|
||||
this.state.codexSubagentRosterByPaneKey.delete(paneKey)
|
||||
this.state.codexLeadStateByPaneKey.delete(paneKey)
|
||||
this.state.codexAsyncQuestionsByPaneKey.delete(paneKey)
|
||||
} else if (deleted.payload.agentType === 'claude') {
|
||||
this.state.claudeSubagentRosterByPaneKey.delete(paneKey)
|
||||
this.state.claudeLeadStateByPaneKey.delete(paneKey)
|
||||
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { normalizeHookPayload } from '../../../../../../shared/agent-hook-listener/normalization/normalize-hook-payload'
|
||||
import { createHookListenerState } from '../../../../../../shared/agent-hook-listener/listener-state'
|
||||
import { buildRelayHookEnvelope } from '../../../../../../wsl-guest/agent-hook-envelope-build'
|
||||
import { AgentHookServer, _internals } from '../../../agent-hook-server'
|
||||
import { PANE, buildBody } from '../../server.test-fixtures'
|
||||
|
||||
vi.mock('../../../../../telemetry/client', () => ({ track: vi.fn() }))
|
||||
vi.mock('../../../../../telemetry/cohort-classifier', () => ({
|
||||
getCohortAtEmit: () => ({ nth_repo_added: 2 })
|
||||
}))
|
||||
|
||||
// Shapes captured from a live Codex 0.166 run.
|
||||
const QUESTIONS = {
|
||||
questions: [
|
||||
{ title: 'Which database should the probe use?', options: ['Postgres', 'SQLite', 'MySQL'] },
|
||||
{ title: 'What should the probe name the new table?' }
|
||||
]
|
||||
}
|
||||
const ASK = {
|
||||
hook_event_name: 'PreToolUse',
|
||||
turn_id: 'turn-1',
|
||||
tool_name: 'request_user_input_async',
|
||||
tool_input: QUESTIONS,
|
||||
tool_use_id: 'call_3_1'
|
||||
}
|
||||
const ACCEPTED = {
|
||||
...ASK,
|
||||
hook_event_name: 'PostToolUse',
|
||||
tool_response: '{"accepted":true}'
|
||||
}
|
||||
const reply = (index: number) => ({
|
||||
hook_event_name: 'UserPromptSubmit',
|
||||
turn_id: 'turn-1',
|
||||
prompt: `<send_user_message_question_reply>\n${JSON.stringify([
|
||||
{
|
||||
answer: 'SQLite',
|
||||
question: QUESTIONS.questions[index]!.title,
|
||||
questionItemId: JSON.stringify(['request_user_input_async', 'call_3_1', index])
|
||||
}
|
||||
])}\n</send_user_message_question_reply>`
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
_internals.resetCachesForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
// The execution host normalizes each hook, then main ingests the relayed row, as for SSH and WSL.
|
||||
function codexPane() {
|
||||
const host = createHookListenerState()
|
||||
const server = new AgentHookServer()
|
||||
return {
|
||||
report(payload: Record<string, unknown>) {
|
||||
const event = normalizeHookPayload(
|
||||
host,
|
||||
'codex',
|
||||
buildBody(payload, { worktreeId: 'folder-workspace' }),
|
||||
'production'
|
||||
)
|
||||
if (!event) {
|
||||
throw new Error('Expected a Codex hook event')
|
||||
}
|
||||
server.ingestRemote(buildRelayHookEnvelope(event, 'codex'), 'wsl:Ubuntu')
|
||||
return { host: event.payload, main: server.getStatusSnapshotForPane(PANE)[0] }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const waitingOnQuestion = {
|
||||
state: 'waiting',
|
||||
toolName: 'request_user_input_async',
|
||||
interactivePrompt: JSON.stringify(QUESTIONS)
|
||||
}
|
||||
|
||||
describe('Codex async questions', () => {
|
||||
it('waits on an open question through the turn until every question is answered', () => {
|
||||
const pane = codexPane()
|
||||
pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' })
|
||||
|
||||
expect(pane.report(ASK).main).toMatchObject(waitingOnQuestion)
|
||||
// Codex accepts the call at once and keeps working; the question is still open.
|
||||
const accepted = pane.report(ACCEPTED)
|
||||
expect(accepted.host).toMatchObject(waitingOnQuestion)
|
||||
expect(accepted.main).toMatchObject(waitingOnQuestion)
|
||||
pane.report({ hook_event_name: 'PreToolUse', turn_id: 'turn-1', tool_name: 'Bash' })
|
||||
// An approval on screen wins over the open question.
|
||||
const approval = pane.report({
|
||||
hook_event_name: 'PermissionRequest',
|
||||
turn_id: 'turn-1',
|
||||
tool_name: 'Bash',
|
||||
tool_input: { command: 'pnpm tc' }
|
||||
}).main
|
||||
expect(approval?.state).toBe('waiting')
|
||||
expect(approval?.interactivePrompt).toContain('"approval"')
|
||||
pane.report({ hook_event_name: 'PostToolUse', turn_id: 'turn-1', tool_name: 'Bash' })
|
||||
expect(pane.report(reply(0)).main).toMatchObject(waitingOnQuestion)
|
||||
|
||||
const answered = pane.report(reply(1)).main
|
||||
expect(answered).toMatchObject({ state: 'working' })
|
||||
expect(answered?.interactivePrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops open questions when the user sends a plain message instead of a reply', () => {
|
||||
const pane = codexPane()
|
||||
pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' })
|
||||
pane.report(ASK)
|
||||
expect(pane.report(ACCEPTED).main).toMatchObject(waitingOnQuestion)
|
||||
|
||||
// Orca's chat card answers an async question as a quoted message, as Codex clients do.
|
||||
const steered = pane.report({
|
||||
hook_event_name: 'UserPromptSubmit',
|
||||
turn_id: 'turn-1',
|
||||
prompt: '> Which database should the probe use?\n\nSQLite'
|
||||
}).main
|
||||
expect(steered).toMatchObject({ state: 'working' })
|
||||
expect(steered?.interactivePrompt).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops an unanswered question when the turn ends', () => {
|
||||
const pane = codexPane()
|
||||
pane.report({ hook_event_name: 'UserPromptSubmit', turn_id: 'turn-1', prompt: 'Set up a db' })
|
||||
pane.report(ASK)
|
||||
expect(pane.report(ACCEPTED).main).toMatchObject(waitingOnQuestion)
|
||||
|
||||
expect(pane.report({ hook_event_name: 'Stop', turn_id: 'turn-1' }).main).toMatchObject({
|
||||
state: 'done'
|
||||
})
|
||||
const next = pane.report({
|
||||
hook_event_name: 'UserPromptSubmit',
|
||||
turn_id: 'turn-2',
|
||||
prompt: 'Next'
|
||||
}).main
|
||||
expect(next).toMatchObject({ state: 'working' })
|
||||
expect(next?.interactivePrompt).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
{"at":4444,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","task_type":"local_agent","subagent_type":"general-purpose","description":"Parent ownership probe"}],"uuid":"parent-task-frame-1","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":4446,"frame":{"type":"system","subtype":"task_started","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","tool_use_id":"toolu_parent","description":"Parent ownership probe","subagent_type":"general-purpose","is_backgrounded":true,"spawn_depth":1,"task_type":"local_agent","prompt":"First use Bash with run_in_background true to run `sleep 100`. Then use Bash in the foreground to run `sleep 100`. Do not run any other commands. When both are done, briefly report that you finished.","uuid":"parent-task-frame-2","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7437,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","task_type":"local_agent","subagent_type":"general-purpose","description":"Parent ownership probe"},{"task_id":"shell-child","run_id":"0mw894jxj-fd21549d","task_type":"local_bash","description":"Sleep 100 seconds in background","parent_task_id":"agent-parent"}],"uuid":"parent-task-frame-3","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7439,"frame":{"type":"system","subtype":"task_started","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","owned_by_subagent":true,"tool_use_id":"toolu_shell","description":"Sleep 100 seconds in background","is_backgrounded":true,"parent_task_id":"agent-parent","task_type":"local_bash","uuid":"parent-task-frame-4","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7446,"frame":{"type":"system","subtype":"task_updated","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","patch":{"status":"killed","end_time":1794167703280},"uuid":"parent-task-frame-5","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7446,"frame":{"type":"system","subtype":"task_notification","task_id":"agent-parent","run_id":"0mw894hmc-1120e0bd","tool_use_id":"toolu_parent","status":"stopped","output_file":"/tmp/claude/tasks/agent-parent.output","summary":"Parent ownership probe","uuid":"parent-task-frame-6","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7446,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[{"task_id":"shell-child","run_id":"0mw894jxj-fd21549d","task_type":"local_bash","description":"Sleep 100 seconds in background","parent_task_id":"agent-parent"}],"uuid":"parent-task-frame-7","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7449,"frame":{"type":"system","subtype":"task_updated","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","patch":{"status":"killed","end_time":1794167703284},"uuid":"parent-task-frame-8","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7450,"frame":{"type":"system","subtype":"task_notification","task_id":"shell-child","run_id":"0mw894jxj-fd21549d","tool_use_id":"toolu_shell","status":"stopped","output_file":"/tmp/claude/tasks/shell-child.output","summary":"Sleep 100 seconds in background","uuid":"parent-task-frame-9","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
{"at":7450,"frame":{"type":"system","subtype":"background_tasks_changed","tasks":[],"uuid":"parent-task-frame-10","session_id":"819cf9f8-e43c-4ad7-b50f-54aa158a726a"}}
|
||||
@@ -6,6 +6,21 @@ afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('bounds the optional persisted title request and ignores its late response', async () => {
|
||||
vi.useFakeTimers()
|
||||
const pending = Promise.withResolvers<string>()
|
||||
const generateSessionTitle = vi.fn(() => pending.promise)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: only the feature-detected method is called.
|
||||
const controls = createClaudeControlSurface({ generateSessionTitle } as unknown as Query)
|
||||
const result = controls.generateSessionTitle!('Repair login')
|
||||
const expired = expect(result).rejects.toThrow('claude generate_session_title request timed out')
|
||||
await vi.advanceTimersByTimeAsync(30_000)
|
||||
await expired
|
||||
pending.resolve('Late title')
|
||||
await expect(result).rejects.toThrow('timed out')
|
||||
expect(generateSessionTitle).toHaveBeenCalledWith('Repair login', { persist: true })
|
||||
})
|
||||
|
||||
describe('createClaudeControlSurface stopTask', () => {
|
||||
it('bounds a lost reply and permits a later stop request', async () => {
|
||||
vi.useFakeTimers()
|
||||
|
||||
@@ -114,6 +114,7 @@ export type ClaudeControlSurface = {
|
||||
getContextUsage: (options?: ClaudeControlOptions) => Promise<unknown>
|
||||
/** Names `sessionId` as the user's rename; refused once the CLI has moved to another session. */
|
||||
renameSession: (title: string, sessionId: string, options?: ClaudeControlOptions) => Promise<void>
|
||||
generateSessionTitle?: (description: string) => Promise<unknown>
|
||||
}
|
||||
|
||||
type InterruptingQuery = {
|
||||
@@ -123,7 +124,16 @@ type InterruptingQuery = {
|
||||
}
|
||||
|
||||
export function createClaudeControlSurface(query: Query): ClaudeControlSurface {
|
||||
const title = 'generateSessionTitle' in query ? query.generateSessionTitle : null
|
||||
return {
|
||||
...(typeof title === 'function'
|
||||
? {
|
||||
generateSessionTitle: (description: string) =>
|
||||
runClaudeControl('generate_session_title', () =>
|
||||
Promise.resolve(title.call(query, description, { persist: true }))
|
||||
)
|
||||
}
|
||||
: {}),
|
||||
interrupt: (options) =>
|
||||
runClaudeControl(
|
||||
'interrupt',
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { AgentSessionRecord } from '../../shared/agent-session/lifecycle/ag
|
||||
import { agentChildWorkLiveness } from '../../shared/agent-status/child-work/agent-status-child-work-liveness'
|
||||
import { conversationCommandBlocked } from '../native-chat/agent-session-wire/operations/structured-conversation-command-admission'
|
||||
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
|
||||
import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture'
|
||||
import { RESUMED_BY_MESSAGE } from './claude-captured-task-frames.test-fixture'
|
||||
import { hostWithParent, parent, producer } from './claude-child-work-producer-harness.test-fixture'
|
||||
|
||||
@@ -54,7 +55,6 @@ async function droppedFromRoster() {
|
||||
expect(records()).toMatchObject([
|
||||
{ membership: 'live', stoppable: true, providerId: 'agent-1', kind: 'agent' }
|
||||
])
|
||||
expect(run.adapter.backgroundTaskState('session-1')).toBeNull()
|
||||
expect(blocked()?.message).toBe('Stop background tasks before using this command.')
|
||||
// Snapshot stop targets before dispatch; settle only acknowledged records.
|
||||
const stop = async (taskId?: string) => {
|
||||
@@ -78,6 +78,46 @@ async function droppedFromRoster() {
|
||||
}
|
||||
|
||||
describe('a background Stop acts on the host child records', () => {
|
||||
it('keeps a stopped owner and its independently stoppable shell attached from real task frames', async () => {
|
||||
const host = hostWithParent()
|
||||
const run = await producer(host)
|
||||
run.replay(PARENT_TASK_STOP.slice(0, 7))
|
||||
const owner = run.records().find((record) => record.kind === 'agent')
|
||||
expect(owner).toMatchObject({ membership: 'settled', outcome: 'cancelled' })
|
||||
expect(run.records().find((record) => record.kind === 'command')).toMatchObject({
|
||||
membership: 'live',
|
||||
stoppable: true,
|
||||
parentChildWorkId: owner?.childWorkId
|
||||
})
|
||||
const targets = agentChildWorkStopTargets(
|
||||
host.getStructuredChildWorkViews(parent),
|
||||
'shell-child'
|
||||
)
|
||||
expect(targets.map((target) => target.providerId)).toEqual(['shell-child'])
|
||||
await run.adapter.stopBackgroundTasks({
|
||||
sessionId: 'session-1',
|
||||
fence: 7,
|
||||
taskIds: targets.map((target) => target.providerId)
|
||||
})
|
||||
expect(run.claude.connections[0]!.calls.filter((call) => call.subtype === 'stop_task')).toEqual(
|
||||
[{ subtype: 'stop_task', params: { taskId: 'shell-child' } }]
|
||||
)
|
||||
run.replay(PARENT_TASK_STOP.slice(7))
|
||||
expect(run.records().find((record) => record.kind === 'command')).toMatchObject({
|
||||
membership: 'settled',
|
||||
outcome: 'cancelled'
|
||||
})
|
||||
|
||||
// Start-only delivery in reverse owner order must converge too; no original tool traffic is replayed.
|
||||
const childFirst = await producer()
|
||||
childFirst.replay([PARENT_TASK_STOP[3]!, PARENT_TASK_STOP[1]!])
|
||||
const resolvedOwner = childFirst.records().find((record) => record.kind === 'agent')
|
||||
expect(childFirst.records().find((record) => record.kind === 'command')).toMatchObject({
|
||||
membership: 'live',
|
||||
parentChildWorkId: resolvedOwner?.childWorkId
|
||||
})
|
||||
})
|
||||
|
||||
it("stops the row's own task, which the records keep after the roster dropped it", async () => {
|
||||
const { records, blocked, stopCalls, stop, basis } = await droppedFromRoster()
|
||||
|
||||
|
||||
@@ -88,3 +88,15 @@ export function liveClaudeTaskRunState(status: unknown): AgentSessionBackgroundT
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES: ReadonlySet<string> = new Set([
|
||||
'task_started',
|
||||
'task_updated',
|
||||
'task_progress',
|
||||
'task_notification'
|
||||
])
|
||||
|
||||
export const CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES: ReadonlySet<string> = new Set([
|
||||
'task_progress',
|
||||
'background_tasks_changed'
|
||||
])
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import type { AgentJournalItemIdentity } from '../../shared/agent-session/journal/agent-session-journal-identity'
|
||||
import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
|
||||
import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
|
||||
|
||||
export type ClaudeBackgroundTaskDescriptor = {
|
||||
identity: AgentJournalItemIdentity
|
||||
generation: number
|
||||
toolUseId?: string
|
||||
linkage: AgentJournalProducerLinkage
|
||||
}
|
||||
|
||||
export type ClaudeBackgroundTaskIndex = {
|
||||
latest?: ClaudeBackgroundTaskDescriptor
|
||||
unresolved?: ClaudeBackgroundTaskDescriptor
|
||||
aliases: Map<string, ClaudeBackgroundTaskDescriptor>
|
||||
}
|
||||
|
||||
export function claudeBackgroundTaskIdentity(
|
||||
taskId: string,
|
||||
generation = 1
|
||||
): AgentJournalItemIdentity {
|
||||
return {
|
||||
provider: 'orca',
|
||||
clientMessageId: `claude-background-task:${taskId}${generation > 1 ? `#${generation}` : ''}`
|
||||
}
|
||||
}
|
||||
|
||||
export function indexClaudeBackgroundTask(
|
||||
index: ClaudeBackgroundTaskIndex,
|
||||
itemId: string,
|
||||
taskId: string,
|
||||
toolUseId: string | undefined,
|
||||
linkage: AgentJournalProducerLinkage
|
||||
): void {
|
||||
const identity = parseAgentJournalItemKey(itemId)
|
||||
if (identity?.provider !== 'orca') {
|
||||
return
|
||||
}
|
||||
const base = `claude-background-task:${taskId}`
|
||||
const generation =
|
||||
identity.clientMessageId === base
|
||||
? 1
|
||||
: identity.clientMessageId.startsWith(`${base}#`)
|
||||
? Number(identity.clientMessageId.slice(base.length + 1))
|
||||
: Number.NaN
|
||||
if (!Number.isSafeInteger(generation) || generation < 1) {
|
||||
return
|
||||
}
|
||||
const descriptor = { identity, generation, toolUseId, linkage }
|
||||
if (!index.latest || generation >= index.latest.generation) {
|
||||
index.latest = descriptor
|
||||
}
|
||||
if (toolUseId === undefined) {
|
||||
if (!index.unresolved || generation >= index.unresolved.generation) {
|
||||
index.unresolved = descriptor
|
||||
}
|
||||
} else {
|
||||
const prior = index.aliases.get(toolUseId)
|
||||
if (!prior || generation >= prior.generation) {
|
||||
index.aliases.set(toolUseId, descriptor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function selectClaudeBackgroundTask(
|
||||
index: ClaudeBackgroundTaskIndex | undefined,
|
||||
toolUseId?: string
|
||||
): ClaudeBackgroundTaskDescriptor | undefined {
|
||||
return toolUseId === undefined
|
||||
? index?.latest
|
||||
: (index?.aliases.get(toolUseId) ?? index?.unresolved)
|
||||
}
|
||||
|
||||
export function resolveClaudeBackgroundTaskDescriptor(
|
||||
journal: StructuredAgentSessionLifecycleJournal,
|
||||
id: string,
|
||||
toolUseId?: string
|
||||
): ClaudeBackgroundTaskDescriptor {
|
||||
const index: ClaudeBackgroundTaskIndex = { aliases: new Map() }
|
||||
journal.visitItems((itemId, _sequence, body) => {
|
||||
if (body.kind !== 'message') {
|
||||
return
|
||||
}
|
||||
const block = body.blocks.find(isBackgroundTaskBlock)
|
||||
if (block?.taskId === id) {
|
||||
indexClaudeBackgroundTask(index, itemId, id, block.parentToolUseId, {})
|
||||
}
|
||||
})
|
||||
return (
|
||||
selectClaudeBackgroundTask(index, toolUseId) ?? {
|
||||
identity: claudeBackgroundTaskIdentity(id, (index.latest?.generation ?? 0) + 1),
|
||||
generation: (index.latest?.generation ?? 0) + 1,
|
||||
toolUseId,
|
||||
linkage: {}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
export function resolveClaudeBackgroundTaskIdentity(
|
||||
journal: StructuredAgentSessionLifecycleJournal,
|
||||
id: string,
|
||||
toolUseId: string | undefined
|
||||
): AgentJournalItemIdentity {
|
||||
return resolveClaudeBackgroundTaskDescriptor(journal, id, toolUseId).identity
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
|
||||
import {
|
||||
classifyClaudeBackgroundTaskKind,
|
||||
@@ -15,16 +16,23 @@ import type {
|
||||
export function observeClaudeBackgroundTaskRoster(
|
||||
tasks: unknown[],
|
||||
rows: Map<string, ClaudeBackgroundTaskRow>,
|
||||
revise: (id: string, change: ClaudeBackgroundTaskChange) => void
|
||||
revise: (id: string, change: ClaudeBackgroundTaskChange) => void,
|
||||
admitOwned?: (id: string, task: Record<string, unknown>) => boolean | void
|
||||
): void {
|
||||
for (const entry of tasks) {
|
||||
const task = record(entry)
|
||||
const id = task === null ? null : taskId(task)
|
||||
if (task && id && task.ambient !== true && task.skip_transcript !== true) {
|
||||
if (admitOwned?.(id, task) === false) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
const row = id === null ? undefined : rows.get(id)
|
||||
if (
|
||||
task === null ||
|
||||
id === null ||
|
||||
task.ambient === true ||
|
||||
task.skip_transcript === true ||
|
||||
!row ||
|
||||
isSettledBackgroundTaskState(row.block.state)
|
||||
) {
|
||||
@@ -37,3 +45,26 @@ export function observeClaudeBackgroundTaskRoster(
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function observeOwnedClaudeBackgroundTaskRoster(input: {
|
||||
tasks: unknown[]
|
||||
rows: Map<string, ClaudeBackgroundTaskRow>
|
||||
invocations: ClaudeTaskInvocations
|
||||
revise: (id: string, change: ClaudeBackgroundTaskChange) => void
|
||||
attribute: (id: string, row: ClaudeBackgroundTaskRow) => void
|
||||
admit: (id: string, task: Record<string, unknown>) => void
|
||||
}): void {
|
||||
observeClaudeBackgroundTaskRoster(input.tasks, input.rows, input.revise, (id, task) => {
|
||||
const selected = input.invocations.selection(task, id)
|
||||
if (!selected?.acceptsStart || selected.invocation.excluded || selected.invocation.monitor) {
|
||||
return false
|
||||
}
|
||||
const row = input.rows.get(id)
|
||||
if (row) {
|
||||
input.attribute(id, row)
|
||||
} else if (selected.invocation.parentTaskId !== undefined) {
|
||||
input.admit(id, task)
|
||||
}
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,60 +8,22 @@ import type {
|
||||
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import type { StructuredAgentSessionLifecycleJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
|
||||
import type { ClaudeBackgroundTaskRow } from './claude-background-task-row-lifecycle'
|
||||
import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { agentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key'
|
||||
import { estimateStructuredAgentSessionItemBytes } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink-estimate'
|
||||
import {
|
||||
claudeBackgroundTaskIdentity,
|
||||
resolveClaudeBackgroundTaskIdentity
|
||||
} from './claude-background-task-identity'
|
||||
export {
|
||||
claudeBackgroundTaskIdentity,
|
||||
resolveClaudeBackgroundTaskIdentity
|
||||
} from './claude-background-task-identity'
|
||||
|
||||
const MAX_RESOLVED_TASK_IDENTITIES = 512
|
||||
const ADMITTED: StructuredAgentSessionSinkAdmission = { accepted: true }
|
||||
|
||||
/** Generation suffixes preserve restarted runs; generation 1 retains the legacy journal key. */
|
||||
export function claudeBackgroundTaskIdentity(
|
||||
taskId: string,
|
||||
generation = 1
|
||||
): AgentJournalItemIdentity {
|
||||
const key =
|
||||
generation > 1
|
||||
? `claude-background-task:${taskId}#${generation}`
|
||||
: `claude-background-task:${taskId}`
|
||||
return { provider: 'orca', clientMessageId: key }
|
||||
}
|
||||
|
||||
export const claudeBackgroundTaskBody = backgroundTaskJournalBody
|
||||
|
||||
export function resolveClaudeBackgroundTaskIdentity(
|
||||
journal: StructuredAgentSessionLifecycleJournal,
|
||||
id: string,
|
||||
toolUseId: string | undefined
|
||||
): AgentJournalItemIdentity {
|
||||
let maxGeneration = 0
|
||||
let matchingGeneration: number | undefined
|
||||
let parentlessGeneration: number | undefined
|
||||
journal.visitItems((itemId, _sequence, body) => {
|
||||
const identity = parseAgentJournalItemKey(itemId)
|
||||
if (!identity || identity.provider !== 'orca') {
|
||||
return
|
||||
}
|
||||
const taskBlock = body.kind === 'message' ? body.blocks.find(isBackgroundTaskBlock) : undefined
|
||||
if (!taskBlock || taskBlock.taskId !== id) {
|
||||
return
|
||||
}
|
||||
const generation = persistedTaskGeneration(identity.clientMessageId, id)
|
||||
if (generation === null) {
|
||||
return
|
||||
}
|
||||
maxGeneration = Math.max(maxGeneration, generation)
|
||||
if (taskBlock.parentToolUseId === toolUseId) {
|
||||
matchingGeneration = Math.max(matchingGeneration ?? 0, generation)
|
||||
} else if (taskBlock.parentToolUseId === undefined) {
|
||||
parentlessGeneration = Math.max(parentlessGeneration ?? 0, generation)
|
||||
}
|
||||
})
|
||||
// A prior parentless row cannot be proved distinct from the later aliased outcome.
|
||||
return claudeBackgroundTaskIdentity(
|
||||
id,
|
||||
matchingGeneration ?? parentlessGeneration ?? (maxGeneration === 0 ? 1 : maxGeneration + 1)
|
||||
)
|
||||
}
|
||||
|
||||
export class ClaudeBackgroundTaskIdentityResolver {
|
||||
private journal: StructuredAgentSessionLifecycleJournal | null = null
|
||||
private epoch: string | null = null
|
||||
@@ -102,19 +64,6 @@ export class ClaudeBackgroundTaskIdentityResolver {
|
||||
}
|
||||
}
|
||||
|
||||
function persistedTaskGeneration(clientMessageId: string, taskId: string): number | null {
|
||||
const base = `claude-background-task:${taskId}`
|
||||
if (clientMessageId === base) {
|
||||
return 1
|
||||
}
|
||||
const prefix = `${base}#`
|
||||
if (!clientMessageId.startsWith(prefix)) {
|
||||
return null
|
||||
}
|
||||
const generation = Number(clientMessageId.slice(prefix.length))
|
||||
return Number.isSafeInteger(generation) && generation > 1 ? generation : null
|
||||
}
|
||||
|
||||
export function writeClaudeBackgroundTaskRow(
|
||||
sink: StructuredAgentSessionEventSink,
|
||||
identities: ClaudeBackgroundTaskIdentityResolver,
|
||||
@@ -127,7 +76,7 @@ export function writeClaudeBackgroundTaskRow(
|
||||
lifecycle = false
|
||||
): StructuredAgentSessionSinkAdmission {
|
||||
const body = claudeBackgroundTaskBody(row.block)
|
||||
const serialized = JSON.stringify(body)
|
||||
const serialized = JSON.stringify([body, row.linkage])
|
||||
if (serialized === row.lastSerialized) {
|
||||
return ADMITTED
|
||||
}
|
||||
@@ -135,16 +84,42 @@ export function writeClaudeBackgroundTaskRow(
|
||||
const identity = claudeBackgroundTaskIdentity(id, row.generation)
|
||||
// A reused row belongs to the current run, so it must count as executing.
|
||||
const appendOptions = {
|
||||
...row.linkage,
|
||||
turnScope: turnScope(),
|
||||
executes: true as const,
|
||||
...(lifecycle ? { lifecycle: true } : {})
|
||||
}
|
||||
const publishOptions = lifecycle ? { lifecycle: true } : {}
|
||||
const toolUseId = row.block.parentToolUseId
|
||||
const resolveIdentity = (journal: StructuredAgentSessionLifecycleJournal) =>
|
||||
identities.resolve(journal, id, row.toolUseId)
|
||||
identities.resolve(journal, id, toolUseId)
|
||||
const appendAndPublish = sink.tryAppendResolvedItemAndPublish
|
||||
let admission: StructuredAgentSessionSinkAdmission
|
||||
if (appendAndPublish) {
|
||||
if (sink.tryReviseResolvedItemAndPublish) {
|
||||
const identitySizeBound = claudeBackgroundTaskIdentity(id, Number.MAX_SAFE_INTEGER)
|
||||
// A saved alias is at most512 characters, each at most6 JSON bytes.
|
||||
const reservedBytes =
|
||||
estimateStructuredAgentSessionItemBytes(identitySizeBound, body) + 512 * 6 + 64
|
||||
admission = sink.tryReviseResolvedItemAndPublish(
|
||||
reservedBytes,
|
||||
(journal) => {
|
||||
const resolved = resolveIdentity(journal)
|
||||
const saved = journal.itemBody(agentJournalItemKey(resolved))
|
||||
const savedBlock =
|
||||
saved?.kind === 'message' ? saved.blocks.find(isBackgroundTaskBlock) : undefined
|
||||
const block = body.kind === 'message' ? body.blocks.find(isBackgroundTaskBlock) : undefined
|
||||
const alias = block?.parentToolUseId ?? savedBlock?.parentToolUseId
|
||||
return {
|
||||
identity: resolved,
|
||||
body:
|
||||
block && alias && block.parentToolUseId === undefined
|
||||
? claudeBackgroundTaskBody({ ...block, parentToolUseId: alias })
|
||||
: body
|
||||
}
|
||||
},
|
||||
appendOptions
|
||||
)
|
||||
} else if (appendAndPublish) {
|
||||
// Budget for any safe generation suffix before the deferred sink resolves its durable identity.
|
||||
const identitySizeBound = claudeBackgroundTaskIdentity(id, Number.MAX_SAFE_INTEGER)
|
||||
admission = appendAndPublish(identitySizeBound, body, resolveIdentity, appendOptions)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ClaudeTaskInvocation } from './claude-task-invocations'
|
||||
import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import {
|
||||
canReplaceBackgroundTaskState,
|
||||
isSettledBackgroundTaskState
|
||||
@@ -19,6 +21,8 @@ import {
|
||||
|
||||
export type ClaudeBackgroundTaskRow = {
|
||||
block: NativeChatBackgroundTaskBlock
|
||||
linkage?: AgentJournalProducerLinkage
|
||||
invocation?: ClaudeTaskInvocation
|
||||
lastSerialized: string | null
|
||||
/** Immutable alias for persistence/coalescing; the final frame may enrich the block's parent. */
|
||||
toolUseId?: string
|
||||
@@ -208,3 +212,20 @@ export function reviseClaudeBackgroundTaskRow(
|
||||
}
|
||||
row.block = next
|
||||
}
|
||||
|
||||
export function attributeClaudeBackgroundTaskRow(id: string, row: ClaudeBackgroundTaskRow): void {
|
||||
const invocation = row.invocation
|
||||
const toolUseId = invocation?.toolUseId
|
||||
if (toolUseId && row.block.parentToolUseId === undefined) {
|
||||
row.block = { ...row.block, parentToolUseId: toolUseId }
|
||||
}
|
||||
const parent = invocation?.reportedParentTaskId
|
||||
if (parent) {
|
||||
row.linkage = {
|
||||
agentId: id,
|
||||
parentAgentId: parent,
|
||||
producerKind: 'background',
|
||||
...(toolUseId ? { providerParentRef: toolUseId } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES } from './claude-background-task-frames'
|
||||
import type { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import { claudeBackgroundTaskToolUseId } from './claude-background-task-row-lifecycle'
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
@@ -94,3 +97,36 @@ export class ClaudeBackgroundTaskRowWriter {
|
||||
this.identities.clear()
|
||||
}
|
||||
}
|
||||
|
||||
export function createClaudeBackgroundTaskTurnOpener(
|
||||
openOutputTurn: ((frame: Record<string, unknown>, observedAt: number) => void) | undefined,
|
||||
invocations: ClaudeTaskInvocations
|
||||
) {
|
||||
return (
|
||||
journaling: { frame: Record<string, unknown>; observedAt: number } | null,
|
||||
open: boolean,
|
||||
id: string | null,
|
||||
row?: ClaudeBackgroundTaskRow
|
||||
): (() => void) => {
|
||||
const frame = journaling?.frame
|
||||
const invocation =
|
||||
row?.invocation ??
|
||||
(frame && id !== null
|
||||
? (invocations.selection(frame, id)?.invocation ??
|
||||
invocations.get(id, claudeBackgroundTaskToolUseId(frame)))
|
||||
: undefined)
|
||||
return () => {
|
||||
// Task inventory from a known child cannot assert execution of the root.
|
||||
const subtype = frame?.subtype
|
||||
if (
|
||||
journaling &&
|
||||
open &&
|
||||
invocation?.parentTaskId === undefined &&
|
||||
(typeof subtype !== 'string' ||
|
||||
!CLAUDE_BACKGROUND_TASK_SILENT_REFRESH_SUBTYPES.has(subtype))
|
||||
) {
|
||||
openOutputTurn?.(journaling.frame, journaling.observedAt)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
import { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
|
||||
import { isSettledBackgroundTaskState } from '../../shared/native-chat/input/native-chat-background-task-row'
|
||||
import type { StructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import { BoundedMap } from '../../shared/bounded-map'
|
||||
import { record, taskAliasId } from './claude-background-task-frames'
|
||||
import {
|
||||
record,
|
||||
taskAliasId,
|
||||
CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES
|
||||
} from './claude-background-task-frames'
|
||||
import {
|
||||
attributeClaudeBackgroundTaskRow,
|
||||
claudeBackgroundTaskPatchChange,
|
||||
claudeBackgroundTaskToolUseId,
|
||||
canonicalClaudeBackgroundTaskId,
|
||||
@@ -19,31 +25,23 @@ import {
|
||||
ensureClaudeBackgroundTaskRowSlot,
|
||||
type ClaudeBackgroundTaskLedgerSizes
|
||||
} from './claude-background-task-memory'
|
||||
import { ClaudeBackgroundTaskRowWriter } from './claude-background-task-row-writer'
|
||||
import {
|
||||
ClaudeBackgroundTaskRowWriter,
|
||||
createClaudeBackgroundTaskTurnOpener
|
||||
} from './claude-background-task-row-writer'
|
||||
import { observeClaudeBackgroundTaskStart } from './claude-background-task-start'
|
||||
import { observeClaudeBackgroundTaskRoster } from './claude-background-task-roster'
|
||||
import { observeOwnedClaudeBackgroundTaskRoster } from './claude-background-task-roster'
|
||||
import { ClaudeSubagentIds } from './claude-subagent-id-aliases'
|
||||
import { ClaudeOverflowTerminalRows } from './claude-overflow-terminal-rows'
|
||||
|
||||
const MAX_TASK_ROWS = 64
|
||||
|
||||
const TASK_SUBTYPES: ReadonlySet<string> = new Set([
|
||||
'task_started',
|
||||
'task_updated',
|
||||
'task_progress',
|
||||
'task_notification'
|
||||
])
|
||||
|
||||
const SILENT_ROW_REFRESH_SUBTYPES: ReadonlySet<string> = new Set([
|
||||
'task_progress',
|
||||
'background_tasks_changed'
|
||||
])
|
||||
|
||||
export type ClaudeBackgroundTaskRowsDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
/** Require a forwarded top-level invocation on first admission to exclude nested children. */
|
||||
isForwardedParentTool: (toolUseId: string) => boolean
|
||||
/** Recover earlier-run subagent ownership when Claude does not repeat its announcement. */
|
||||
taskInvocations?: ClaudeTaskInvocations
|
||||
rosteredByEarlierRun?: (taskId: string) => boolean
|
||||
/** Reopen provider-resumed turns before journaling output so the session reports working. */
|
||||
openOutputTurn?: (frame: Record<string, unknown>, observedAt: number) => void
|
||||
@@ -56,13 +54,17 @@ export type ClaudeBackgroundTaskRowsDeps = {
|
||||
export class ClaudeBackgroundTaskRows {
|
||||
private readonly rows = new Map<string, ClaudeBackgroundTaskRow>()
|
||||
private readonly writer: ClaudeBackgroundTaskRowWriter
|
||||
private readonly openTurn: ReturnType<typeof createClaudeBackgroundTaskTurnOpener>
|
||||
private readonly overflowTerminalRows: ClaudeOverflowTerminalRows
|
||||
private readonly ledgers = new ClaudeBackgroundTaskLedgers()
|
||||
private readonly ids = new ClaudeSubagentIds()
|
||||
private readonly now: () => number
|
||||
private readonly taskInvocations: ClaudeTaskInvocations
|
||||
|
||||
constructor(private readonly deps: ClaudeBackgroundTaskRowsDeps) {
|
||||
this.taskInvocations = deps.taskInvocations ?? new ClaudeTaskInvocations()
|
||||
this.now = deps.now ?? (() => Date.now())
|
||||
this.openTurn = createClaudeBackgroundTaskTurnOpener(deps.openOutputTurn, this.taskInvocations)
|
||||
this.writer = new ClaudeBackgroundTaskRowWriter(
|
||||
deps.sink,
|
||||
deps.turnScope,
|
||||
@@ -87,6 +89,7 @@ export class ClaudeBackgroundTaskRows {
|
||||
private journaling: { frame: Record<string, unknown>; observedAt: number } | null = null
|
||||
|
||||
observe(message: Record<string, unknown>, observedAt: number = this.now()): boolean {
|
||||
this.taskInvocations.observe(message)
|
||||
this.journaling = { frame: message, observedAt }
|
||||
// Claude wakes the lead for any task the lead launched, rowless subagents included; open that turn at the notification, once per frame.
|
||||
const toolUseId =
|
||||
@@ -101,7 +104,8 @@ export class ClaudeBackgroundTaskRows {
|
||||
if (frameId) {
|
||||
this.wakeFrames.set(frameId, true)
|
||||
}
|
||||
this.deps.openOutputTurn?.(message, observedAt)
|
||||
const id = canonicalClaudeBackgroundTaskId(message, this.ids)
|
||||
this.openTurn(this.journaling, true, id)()
|
||||
}
|
||||
try {
|
||||
return this.observeFrame(message)
|
||||
@@ -111,10 +115,10 @@ export class ClaudeBackgroundTaskRows {
|
||||
}
|
||||
|
||||
/** Monitor results may precede announcements; their notifications belong to the tool call. */
|
||||
observeMonitorToolResult(taskId: unknown): void {
|
||||
observeMonitorToolResult(taskId: unknown, toolUseId?: string): void {
|
||||
const id = taskAliasId(taskId)
|
||||
if (id !== undefined) {
|
||||
this.ledgers.rememberForeign(id, 'ambient')
|
||||
this.taskInvocations.excludeMonitor(id, toolUseId)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,28 +130,46 @@ export class ClaudeBackgroundTaskRows {
|
||||
if (!Array.isArray(message.tasks)) {
|
||||
return false
|
||||
}
|
||||
observeClaudeBackgroundTaskRoster(message.tasks, this.rows, (id, change) =>
|
||||
this.revise(id, change)
|
||||
)
|
||||
observeOwnedClaudeBackgroundTaskRoster({
|
||||
tasks: message.tasks,
|
||||
rows: this.rows,
|
||||
invocations: this.taskInvocations,
|
||||
revise: (id, change) => this.revise(id, change),
|
||||
attribute: attributeClaudeBackgroundTaskRow,
|
||||
admit: (id, task) => {
|
||||
if (!this.ledgers.terminalTaskIds.has(id)) {
|
||||
this.observeStart(id, task, true)
|
||||
}
|
||||
}
|
||||
})
|
||||
return true
|
||||
}
|
||||
if (typeof message.subtype !== 'string' || !TASK_SUBTYPES.has(message.subtype)) {
|
||||
if (
|
||||
typeof message.subtype !== 'string' ||
|
||||
!CLAUDE_BACKGROUND_TASK_ROW_SUBTYPES.has(message.subtype)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const id = canonicalClaudeBackgroundTaskId(message, this.ids)
|
||||
if (id === null) {
|
||||
return false
|
||||
}
|
||||
const selected = this.taskInvocations.selection(message, id)
|
||||
if (selected?.invocation.excluded || selected?.invocation.monitor) {
|
||||
return true
|
||||
}
|
||||
if (selected?.current === false) {
|
||||
if (message.subtype !== 'task_notification') {
|
||||
return true
|
||||
}
|
||||
const generation = this.ledgers.generations.next(id)
|
||||
const row = newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation)
|
||||
row.invocation = selected.invocation
|
||||
this.writeRow(id, row)
|
||||
return true
|
||||
}
|
||||
if (message.subtype === 'task_started') {
|
||||
return observeClaudeBackgroundTaskStart({
|
||||
id,
|
||||
message,
|
||||
rows: this.rows,
|
||||
ledgers: this.ledgers,
|
||||
isForwardedParentTool: this.deps.isForwardedParentTool,
|
||||
openRow: (taskId, frame) => this.openRow(taskId, frame),
|
||||
maxRows: MAX_TASK_ROWS
|
||||
})
|
||||
return this.observeStart(id, message)
|
||||
}
|
||||
if (this.ledgers.foreign.has(id)) {
|
||||
return true
|
||||
@@ -162,6 +184,28 @@ export class ClaudeBackgroundTaskRows {
|
||||
return this.observePatch(id, message)
|
||||
}
|
||||
|
||||
private observeStart(id: string, message: Record<string, unknown>, roster = false): boolean {
|
||||
const selected = this.taskInvocations.selection(message, id)
|
||||
if (!selected?.acceptsStart || selected.invocation.excluded || selected.invocation.monitor) {
|
||||
return true
|
||||
}
|
||||
return observeClaudeBackgroundTaskStart({
|
||||
id,
|
||||
message: {
|
||||
...message,
|
||||
...(roster ? { is_backgrounded: true } : {}),
|
||||
tool_use_id: selected.invocation.toolUseId
|
||||
},
|
||||
owned: selected.invocation.parentTaskId !== undefined,
|
||||
rows: this.rows,
|
||||
ledgers: this.ledgers,
|
||||
isForwardedParentTool: this.deps.isForwardedParentTool,
|
||||
openRow: (taskId, frame) => this.openRow(taskId, frame),
|
||||
refresh: (id) => this.write(id),
|
||||
maxRows: MAX_TASK_ROWS
|
||||
})
|
||||
}
|
||||
|
||||
settleSession(): void {
|
||||
for (const [id, row] of this.rows) {
|
||||
if (!isSettledBackgroundTaskState(row.block.state)) {
|
||||
@@ -180,13 +224,13 @@ export class ClaudeBackgroundTaskRows {
|
||||
this.ids.clear()
|
||||
}
|
||||
|
||||
retryPendingWrites() {
|
||||
return this.writer.retryPendingWrites()
|
||||
}
|
||||
retryPendingWrites = () => this.writer.retryPendingWrites()
|
||||
|
||||
private openRow(id: string, message: Record<string, unknown>): void {
|
||||
const generation = this.ledgers.generations.next(id)
|
||||
this.rows.set(id, newClaudeBackgroundTaskRow(id, message, this.now(), generation))
|
||||
const row = newClaudeBackgroundTaskRow(id, message, this.now(), generation)
|
||||
row.invocation = this.taskInvocations.get(id, claudeBackgroundTaskToolUseId(message))
|
||||
this.rows.set(id, row)
|
||||
this.write(id)
|
||||
}
|
||||
|
||||
@@ -218,10 +262,9 @@ export class ClaudeBackgroundTaskRows {
|
||||
return true
|
||||
}
|
||||
const generation = this.ledgers.generations.next(id)
|
||||
this.rows.set(
|
||||
id,
|
||||
newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation)
|
||||
)
|
||||
const row = newClaudeBackgroundTaskRowFromNotification(id, message, this.now(), generation)
|
||||
row.invocation = this.taskInvocations.get(id, claudeBackgroundTaskToolUseId(message))
|
||||
this.rows.set(id, row)
|
||||
this.write(id)
|
||||
return true
|
||||
}
|
||||
@@ -230,6 +273,7 @@ export class ClaudeBackgroundTaskRows {
|
||||
if (this.ledgers.fallbackTaskIds.has(id)) {
|
||||
const change = claudeBackgroundTaskPatchChange(message)
|
||||
if (change.state && isSettledBackgroundTaskState(change.state)) {
|
||||
this.taskInvocations.settleFrame(id, message)
|
||||
this.ledgers.rememberTerminal(this.rows, id, claudeBackgroundTaskToolUseId(message))
|
||||
this.overflowTerminalRows.observePatch(id, message, change)
|
||||
return true
|
||||
@@ -248,6 +292,7 @@ export class ClaudeBackgroundTaskRows {
|
||||
}
|
||||
const change = claudeBackgroundTaskPatchChange(message)
|
||||
if (change.state && isSettledBackgroundTaskState(change.state)) {
|
||||
this.taskInvocations.settleFrame(id, message)
|
||||
this.ledgers.rememberTerminal(this.rows, id, claudeBackgroundTaskToolUseId(message))
|
||||
}
|
||||
if (row) {
|
||||
@@ -280,23 +325,7 @@ export class ClaudeBackgroundTaskRows {
|
||||
openOutputTurn = true,
|
||||
lifecycle = false
|
||||
): void {
|
||||
const journaling = this.journaling
|
||||
this.writer.write(
|
||||
id,
|
||||
row,
|
||||
() => {
|
||||
// Why: progress and roster ticks refresh the row only. Opening a turn
|
||||
// here flips an idle chat back to working.
|
||||
const subtype = journaling?.frame.subtype
|
||||
if (
|
||||
journaling &&
|
||||
openOutputTurn &&
|
||||
(typeof subtype !== 'string' || !SILENT_ROW_REFRESH_SUBTYPES.has(subtype))
|
||||
) {
|
||||
this.deps.openOutputTurn?.(journaling.frame, journaling.observedAt)
|
||||
}
|
||||
},
|
||||
lifecycle
|
||||
)
|
||||
attributeClaudeBackgroundTaskRow(id, row)
|
||||
this.writer.write(id, row, this.openTurn(this.journaling, openOutputTurn, id, row), lifecycle)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
} from './claude-background-task-memory'
|
||||
import { isClaudeSubagentTask } from './claude-subagent-task-frames'
|
||||
|
||||
export function observeClaudeBackgroundTaskStart(input: {
|
||||
type ClaudeBackgroundTaskStartInput = {
|
||||
id: string
|
||||
message: Record<string, unknown>
|
||||
rows: Map<string, ClaudeBackgroundTaskRow>
|
||||
@@ -20,7 +20,14 @@ export function observeClaudeBackgroundTaskStart(input: {
|
||||
isForwardedParentTool: (toolUseId: string) => boolean
|
||||
openRow: (id: string, message: Record<string, unknown>) => void
|
||||
maxRows: number
|
||||
}): boolean {
|
||||
}
|
||||
|
||||
export function observeClaudeBackgroundTaskStart(
|
||||
input: ClaudeBackgroundTaskStartInput & {
|
||||
owned: boolean
|
||||
refresh: (id: string, row: ClaudeBackgroundTaskRow) => void
|
||||
}
|
||||
): boolean {
|
||||
const { id, message, rows, ledgers } = input
|
||||
if (ledgers.fallbackTaskIds.has(id)) {
|
||||
if (ledgers.terminalTaskIds.has(id)) {
|
||||
@@ -39,10 +46,6 @@ export function observeClaudeBackgroundTaskStart(input: {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if (message.ambient === true || message.skip_transcript === true) {
|
||||
ledgers.rememberForeign(id, 'ambient')
|
||||
return true
|
||||
}
|
||||
if (isClaudeSubagentTask(message)) {
|
||||
ledgers.rememberForeign(id, 'roster')
|
||||
return true
|
||||
@@ -57,6 +60,7 @@ export function observeClaudeBackgroundTaskStart(input: {
|
||||
ledgers.foreign.delete(id)
|
||||
// A live task's duplicate announcement is redelivery, not a new run.
|
||||
if (!isSettledBackgroundTaskState(existing.block.state)) {
|
||||
input.refresh(id, existing)
|
||||
return true
|
||||
}
|
||||
if (shouldRestartClaudeBackgroundTaskRow(existing, message)) {
|
||||
@@ -81,7 +85,7 @@ export function observeClaudeBackgroundTaskStart(input: {
|
||||
ledgers.foreign.delete(id)
|
||||
const toolUseId = claudeBackgroundTaskToolUseId(message)
|
||||
// Absence of a parent is not evidence of an unforwarded parent.
|
||||
if (toolUseId !== undefined && !input.isForwardedParentTool(toolUseId)) {
|
||||
if (toolUseId !== undefined && !input.owned && !input.isForwardedParentTool(toolUseId)) {
|
||||
ledgers.rememberForeign(id, 'sidechain')
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -161,3 +161,78 @@ describe('a typed background-task row opens the turn it resumes', () => {
|
||||
expect(projected(items())).toBe('idle')
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps an alias-only owned notification idle even when its alias was forwarded at the root', () => {
|
||||
const { translator, items } = harness()
|
||||
spawnToolCall(translator)
|
||||
translator.handle(
|
||||
systemFrame('owned-start', {
|
||||
subtype: 'task_started',
|
||||
task_id: 'owned',
|
||||
tool_use_id: TOOL,
|
||||
parent_task_id: 'owner',
|
||||
task_type: 'local_bash',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
settleTurn(translator)
|
||||
translator.handle(
|
||||
systemFrame('owned-terminal', {
|
||||
subtype: 'task_notification',
|
||||
tool_use_id: TOOL,
|
||||
status: 'completed',
|
||||
summary: 'Finished child'
|
||||
})
|
||||
)
|
||||
expect(items().find((item) => item.itemId.includes('owned'))?.body).toMatchObject({
|
||||
kind: 'message',
|
||||
blocks: expect.arrayContaining([
|
||||
expect.objectContaining({ type: 'background-task', taskId: 'owned', state: 'done' })
|
||||
])
|
||||
})
|
||||
expect(projected(items())).toBe('idle')
|
||||
translator.dispose()
|
||||
})
|
||||
|
||||
it('keeps owned terminal overflow writes idle without a retained row invocation', () => {
|
||||
const { translator, items } = harness()
|
||||
for (let index = 0; index < 65; index += 1) {
|
||||
translator.handle(
|
||||
systemFrame(`owned-start-${index}`, {
|
||||
subtype: 'task_started',
|
||||
task_id: `owned-${index}`,
|
||||
parent_task_id: 'owner',
|
||||
task_type: 'local_bash',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
}
|
||||
settleTurn(translator)
|
||||
translator.handle(
|
||||
systemFrame('overflow-owned-patch', {
|
||||
subtype: 'task_updated',
|
||||
task_id: 'owned-64',
|
||||
patch: { status: 'failed' }
|
||||
})
|
||||
)
|
||||
translator.handle(
|
||||
systemFrame('overflow-owned-orphan', {
|
||||
subtype: 'task_notification',
|
||||
task_id: 'owned-terminal-only',
|
||||
parent_task_id: 'owner',
|
||||
status: 'completed'
|
||||
})
|
||||
)
|
||||
const terminal = items().filter(
|
||||
(item) =>
|
||||
item.body.kind === 'message' &&
|
||||
item.body.blocks.some(
|
||||
(block) =>
|
||||
block.type === 'background-task' &&
|
||||
['owned-64', 'owned-terminal-only'].includes(block.taskId)
|
||||
)
|
||||
)
|
||||
expect(terminal).toHaveLength(2)
|
||||
expect(projected(items())).toBe('idle')
|
||||
translator.dispose()
|
||||
})
|
||||
|
||||
@@ -1,14 +1,7 @@
|
||||
// Roster changes, turn endings and spawn results cannot settle a child.
|
||||
|
||||
import type {
|
||||
AgentChildWorkKind,
|
||||
AgentChildWorkOperation,
|
||||
AgentChildWorkOutcome
|
||||
} from '../../shared/agent-status/child-work/agent-status-child-work'
|
||||
import type {
|
||||
AgentChildWorkEvidence,
|
||||
AgentChildWorkLiveObservation
|
||||
} from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
|
||||
import { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
|
||||
import {
|
||||
classifyClaudeBackgroundTaskKind,
|
||||
liveClaudeTaskRunState,
|
||||
@@ -21,83 +14,34 @@ import {
|
||||
taskUsageTotalTokens,
|
||||
terminalClaudeTaskRunState
|
||||
} from './claude-background-task-frames'
|
||||
import { isClaudeSubagentTask } from './claude-subagent-task-frames'
|
||||
import { claudeStartedTaskKind } from './claude-subagent-task-frames'
|
||||
import { ClaudeAgentWaitCalls } from './claude-agent-wait-calls'
|
||||
import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations'
|
||||
import {
|
||||
claudeChildWorkOutcome,
|
||||
claudeChildWorkObservation,
|
||||
type DecodedClaudeTask,
|
||||
type EndedClaudeTask,
|
||||
claudeTaskProgressFacts,
|
||||
type ClaudeTaskFacts
|
||||
} from './claude-child-work-evidence'
|
||||
|
||||
type DecodedClaudeTask = {
|
||||
kind: AgentChildWorkKind
|
||||
backgrounded: boolean
|
||||
/** Monitors stay monitoring until the provider reports them running. */
|
||||
running: boolean
|
||||
name?: string
|
||||
description?: string
|
||||
toolUseId?: string
|
||||
/** Runs `orca orchestration check --wait`: waiting on worker agents, so agent work. */
|
||||
awaitsAgents?: true
|
||||
}
|
||||
|
||||
type ClaudeToolOwner = (toolUseId: string) => string | null
|
||||
|
||||
type PendingEdge = (observedAt: number) => AgentChildWorkEvidence
|
||||
|
||||
function observation(
|
||||
id: string,
|
||||
task: DecodedClaudeTask,
|
||||
facts: ClaudeTaskFacts,
|
||||
observedAt: number,
|
||||
waiting: boolean
|
||||
): AgentChildWorkLiveObservation {
|
||||
const operation: AgentChildWorkOperation | undefined = facts.toolName
|
||||
? { toolName: facts.toolName, basis: 'reported', observedAt }
|
||||
: task.awaitsAgents
|
||||
? {
|
||||
toolName: 'Bash',
|
||||
input: ORCA_ORCHESTRATION_WAIT_COMMAND,
|
||||
basis: 'reported',
|
||||
observedAt
|
||||
}
|
||||
: undefined
|
||||
return {
|
||||
handle: {
|
||||
idKind: 'task_id',
|
||||
id,
|
||||
...(task.toolUseId !== undefined ? { runId: task.toolUseId } : {})
|
||||
},
|
||||
kind: task.kind,
|
||||
residency: task.backgrounded ? 'background' : 'foreground',
|
||||
state: waiting ? 'waiting' : task.running || task.kind !== 'monitor' ? 'working' : 'monitoring',
|
||||
...(task.name ? { name: task.name, agentType: task.name } : {}),
|
||||
...(task.description ? { description: task.description } : {}),
|
||||
...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}),
|
||||
...(operation ? { operation } : {}),
|
||||
...(facts.lastMessage ? { lastMessage: facts.lastMessage } : {}),
|
||||
// Only background tasks expose a stop target.
|
||||
stoppable: task.backgrounded
|
||||
}
|
||||
}
|
||||
|
||||
export class ClaudeChildWorkDecoder {
|
||||
private readonly live = new Map<string, DecodedClaudeTask>()
|
||||
/** Retain ended runs for the session to distinguish wakes from late starts. */
|
||||
private readonly ended = new Map<
|
||||
string,
|
||||
{
|
||||
run: string | undefined
|
||||
outcome: AgentChildWorkOutcome
|
||||
task?: DecodedClaudeTask
|
||||
}
|
||||
>()
|
||||
private readonly ended = new Map<string, EndedClaudeTask>()
|
||||
private readonly childrenByOwner = new Map<string, Set<string>>()
|
||||
private waiting: ReadonlySet<string> = new Set()
|
||||
private pending: PendingEdge[] = []
|
||||
private readonly agentWaits = new ClaudeAgentWaitCalls()
|
||||
/** `ownerOf` names the subagent that made a child tool call; an ending task wakes it. */
|
||||
constructor(readonly taskInvocations = new ClaudeTaskInvocations()) {}
|
||||
|
||||
observe(message: Record<string, unknown>, ownerOf?: ClaudeToolOwner): void {
|
||||
this.taskInvocations.observe(message)
|
||||
if (message.type === 'assistant') {
|
||||
this.agentWaits.observe(message)
|
||||
return
|
||||
@@ -105,10 +49,31 @@ export class ClaudeChildWorkDecoder {
|
||||
if (message.type !== 'system') {
|
||||
return
|
||||
}
|
||||
if (message.subtype === 'background_tasks_changed') {
|
||||
if (Array.isArray(message.tasks)) {
|
||||
for (const entry of message.tasks) {
|
||||
const task = record(entry)
|
||||
const id = task && taskId(task)
|
||||
if (
|
||||
task &&
|
||||
id &&
|
||||
!this.ended.has(id) &&
|
||||
this.taskInvocations.parentOf(id, taskAliasId(task.tool_use_id))
|
||||
) {
|
||||
this.started(id, task, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
const id = taskId(message)
|
||||
if (!id) {
|
||||
return
|
||||
}
|
||||
const selected = this.taskInvocations.selection(message, id)
|
||||
if (selected && (!selected.current || selected.invocation.excluded)) {
|
||||
return
|
||||
}
|
||||
switch (message.subtype) {
|
||||
case 'task_started':
|
||||
this.started(id, message)
|
||||
@@ -145,8 +110,10 @@ export class ClaudeChildWorkDecoder {
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.taskInvocations.clear()
|
||||
this.live.clear()
|
||||
this.ended.clear()
|
||||
this.childrenByOwner.clear()
|
||||
this.agentWaits.clear()
|
||||
this.waiting = new Set()
|
||||
this.pending.push((observedAt) => ({ type: 'session-ended', observedAt }))
|
||||
@@ -158,12 +125,14 @@ export class ClaudeChildWorkDecoder {
|
||||
return pending.map((edge) => edge(observedAt))
|
||||
}
|
||||
|
||||
private started(id: string, message: Record<string, unknown>): void {
|
||||
const toolUseId = taskAliasId(message.tool_use_id)
|
||||
const awaitsAgents = this.agentWaits.take(toolUseId)
|
||||
if (message.ambient === true || message.skip_transcript === true) {
|
||||
private started(id: string, message: Record<string, unknown>, roster = false): void {
|
||||
const selection = this.taskInvocations.selection(message, id)
|
||||
if (!selection?.acceptsStart || selection.invocation.excluded) {
|
||||
return
|
||||
}
|
||||
const invocation = selection.invocation
|
||||
const toolUseId = invocation.toolUseId
|
||||
const awaitsAgents = this.agentWaits.take(toolUseId)
|
||||
const existing = this.live.get(id)
|
||||
const ended = existing ? undefined : this.ended.get(id)
|
||||
const restart = ended !== undefined
|
||||
@@ -171,12 +140,13 @@ export class ClaudeChildWorkDecoder {
|
||||
if (ended?.run !== undefined && ended.run === toolUseId && ended.outcome !== 'succeeded') {
|
||||
return
|
||||
}
|
||||
const kind = startedTaskKind(message)
|
||||
const kind = claudeStartedTaskKind(message)
|
||||
this.upsert(
|
||||
id,
|
||||
{
|
||||
kind: kind !== 'unknown' ? kind : (existing?.kind ?? 'unknown'),
|
||||
backgrounded:
|
||||
roster ||
|
||||
message.is_backgrounded === true ||
|
||||
kind === 'workflow' ||
|
||||
kind === 'monitor' ||
|
||||
@@ -185,16 +155,22 @@ export class ClaudeChildWorkDecoder {
|
||||
name: taskName(message) ?? existing?.name,
|
||||
description: taskDescription(message.description) ?? existing?.description,
|
||||
toolUseId: toolUseId ?? existing?.toolUseId,
|
||||
parentTaskId: invocation.parentTaskId,
|
||||
...(awaitsAgents || existing?.awaitsAgents ? { awaitsAgents: true as const } : {})
|
||||
},
|
||||
{},
|
||||
restart
|
||||
restart,
|
||||
roster
|
||||
)
|
||||
}
|
||||
|
||||
/** Claude resumes a finished subagent when a task it launched notifies; show it working from that frame, not its restart a moment later. */
|
||||
private wakeOwner(toolUseId: string | undefined, ownerOf: ClaudeToolOwner | undefined): void {
|
||||
const ownerId = toolUseId ? ownerOf?.(toolUseId) : null
|
||||
private wakeOwner(
|
||||
toolUseId: string | undefined,
|
||||
ownerOf: ClaudeToolOwner | undefined,
|
||||
parentTaskId?: string
|
||||
): void {
|
||||
const ownerId = parentTaskId ?? (toolUseId ? ownerOf?.(toolUseId) : null)
|
||||
const owner = ownerId ? this.ended.get(ownerId) : undefined
|
||||
if (ownerId && owner?.outcome === 'succeeded' && owner.task?.kind === 'agent') {
|
||||
this.upsert(ownerId, { ...owner.task, running: true }, {}, true)
|
||||
@@ -207,11 +183,8 @@ export class ClaudeChildWorkDecoder {
|
||||
return
|
||||
}
|
||||
// Progress descriptions describe the current activity, not the task.
|
||||
this.upsert(
|
||||
id,
|
||||
{ ...task, name: task.name ?? taskName(message) },
|
||||
claudeTaskProgressFacts(message)
|
||||
)
|
||||
const name = task.name ?? taskName(message)
|
||||
this.upsert(id, { ...task, name }, claudeTaskProgressFacts(message))
|
||||
}
|
||||
|
||||
private updated(
|
||||
@@ -230,7 +203,6 @@ export class ClaudeChildWorkDecoder {
|
||||
}
|
||||
return
|
||||
}
|
||||
// Late updates cannot reopen an ended task.
|
||||
if (!existing && this.ended.has(id)) {
|
||||
return
|
||||
}
|
||||
@@ -251,6 +223,7 @@ export class ClaudeChildWorkDecoder {
|
||||
name: name ?? existing?.name,
|
||||
description: description ?? existing?.description,
|
||||
toolUseId: existing?.toolUseId,
|
||||
parentTaskId: existing?.parentTaskId,
|
||||
...(existing?.awaitsAgents ? { awaitsAgents: true as const } : {})
|
||||
},
|
||||
{},
|
||||
@@ -262,11 +235,44 @@ export class ClaudeChildWorkDecoder {
|
||||
id: string,
|
||||
task: DecodedClaudeTask,
|
||||
facts: ClaudeTaskFacts,
|
||||
restart = false
|
||||
restart = false,
|
||||
unchangedRoster = false
|
||||
): void {
|
||||
if (unchangedRoster && JSON.stringify(task) === JSON.stringify(this.live.get(id))) {
|
||||
return
|
||||
}
|
||||
const ownerBecameLive = !this.live.has(id) || restart
|
||||
this.ended.delete(id)
|
||||
this.removeOwnerIndex(id)
|
||||
this.live.set(id, task)
|
||||
if (task.parentTaskId) {
|
||||
const children = this.childrenByOwner.get(task.parentTaskId) ?? new Set<string>()
|
||||
children.add(id)
|
||||
this.childrenByOwner.set(task.parentTaskId, children)
|
||||
}
|
||||
this.report(id, task, facts, restart)
|
||||
// Admission can resolve a child's raw owner only after that owner's live edge.
|
||||
if (!ownerBecameLive) {
|
||||
return
|
||||
}
|
||||
for (const childId of this.childrenByOwner.get(id) ?? []) {
|
||||
const child = this.live.get(childId)
|
||||
if (child && childId !== id) {
|
||||
this.report(childId, child, {})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private removeOwnerIndex(id: string): void {
|
||||
const parent = this.live.get(id)?.parentTaskId
|
||||
if (parent === undefined) {
|
||||
return
|
||||
}
|
||||
const children = this.childrenByOwner.get(parent)
|
||||
children?.delete(id)
|
||||
if (children?.size === 0) {
|
||||
this.childrenByOwner.delete(parent)
|
||||
}
|
||||
}
|
||||
|
||||
/** Read waiting state at drain so all queued live edges agree. */
|
||||
@@ -274,7 +280,7 @@ export class ClaudeChildWorkDecoder {
|
||||
this.pending.push((observedAt) => ({
|
||||
type: 'live',
|
||||
observedAt,
|
||||
child: observation(id, task, facts, observedAt, this.waiting.has(id)),
|
||||
child: claudeChildWorkObservation(id, task, facts, observedAt, this.waiting.has(id)),
|
||||
...(restart ? { restart: true } : {})
|
||||
}))
|
||||
}
|
||||
@@ -290,6 +296,8 @@ export class ClaudeChildWorkDecoder {
|
||||
ownerOf?: ClaudeToolOwner
|
||||
): void {
|
||||
const task = this.live.get(id)
|
||||
this.taskInvocations.settle(id, status, reported.runId ?? task?.toolUseId)
|
||||
this.removeOwnerIndex(id)
|
||||
this.live.delete(id)
|
||||
const outcome = claudeChildWorkOutcome(status)
|
||||
this.ended.set(id, {
|
||||
@@ -300,7 +308,7 @@ export class ClaudeChildWorkDecoder {
|
||||
})
|
||||
// Every ending but a stop notifies, which wakes the subagent that launched the task.
|
||||
if (outcome !== 'cancelled') {
|
||||
this.wakeOwner(reported.runId ?? task?.toolUseId, ownerOf)
|
||||
this.wakeOwner(reported.runId ?? task?.toolUseId, ownerOf, task?.parentTaskId)
|
||||
}
|
||||
this.pending.push((observedAt) => ({
|
||||
type: 'ended',
|
||||
@@ -316,10 +324,3 @@ export class ClaudeChildWorkDecoder {
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
/** Releases predating `task_type` still name an agent in `subagent_type`. */
|
||||
function startedTaskKind(message: Record<string, unknown>): AgentChildWorkKind {
|
||||
return isClaudeSubagentTask(message)
|
||||
? 'agent'
|
||||
: classifyClaudeBackgroundTaskKind(message.task_type)
|
||||
}
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { AgentChildWorkOutcome } from '../../shared/agent-status/child-work/agent-status-child-work'
|
||||
import { ORCA_ORCHESTRATION_WAIT_COMMAND } from '../../shared/orca-cli-invocations'
|
||||
import type {
|
||||
AgentChildWorkKind,
|
||||
AgentChildWorkOperation,
|
||||
AgentChildWorkOutcome
|
||||
} from '../../shared/agent-status/child-work/agent-status-child-work'
|
||||
import type {
|
||||
AgentChildWorkEvidence,
|
||||
AgentChildWorkLiveObservation
|
||||
@@ -17,6 +22,62 @@ import {
|
||||
type ClaudeToolUse
|
||||
} from './structured/journal/claude-structured-item-translation'
|
||||
|
||||
export type EndedClaudeTask = {
|
||||
run: string | undefined
|
||||
outcome: AgentChildWorkOutcome
|
||||
task?: DecodedClaudeTask
|
||||
}
|
||||
|
||||
export type DecodedClaudeTask = {
|
||||
kind: AgentChildWorkKind
|
||||
backgrounded: boolean
|
||||
/** Monitors stay monitoring until the provider reports them running. */
|
||||
running: boolean
|
||||
name?: string
|
||||
description?: string
|
||||
toolUseId?: string
|
||||
parentTaskId?: string
|
||||
/** Runs `orca orchestration check --wait`: waiting on worker agents, so agent work. */
|
||||
awaitsAgents?: true
|
||||
}
|
||||
|
||||
export function claudeChildWorkObservation(
|
||||
id: string,
|
||||
task: DecodedClaudeTask,
|
||||
facts: ClaudeTaskFacts,
|
||||
observedAt: number,
|
||||
waiting: boolean
|
||||
): AgentChildWorkLiveObservation {
|
||||
const operation: AgentChildWorkOperation | undefined = facts.toolName
|
||||
? { toolName: facts.toolName, basis: 'reported', observedAt }
|
||||
: task.awaitsAgents
|
||||
? {
|
||||
toolName: 'Bash',
|
||||
input: ORCA_ORCHESTRATION_WAIT_COMMAND,
|
||||
basis: 'reported',
|
||||
observedAt
|
||||
}
|
||||
: undefined
|
||||
return {
|
||||
handle: {
|
||||
idKind: 'task_id',
|
||||
id,
|
||||
...(task.toolUseId !== undefined ? { runId: task.toolUseId } : {})
|
||||
},
|
||||
...(task.parentTaskId ? { ownerId: task.parentTaskId } : {}),
|
||||
kind: task.kind,
|
||||
residency: task.backgrounded ? 'background' : 'foreground',
|
||||
state: waiting ? 'waiting' : task.running || task.kind !== 'monitor' ? 'working' : 'monitoring',
|
||||
...(task.name ? { name: task.name, agentType: task.name } : {}),
|
||||
...(task.description ? { description: task.description } : {}),
|
||||
...(facts.totalTokens !== undefined ? { totalTokens: facts.totalTokens } : {}),
|
||||
...(operation ? { operation } : {}),
|
||||
...(facts.lastMessage ? { lastMessage: facts.lastMessage } : {}),
|
||||
// Only background tasks expose a stop target.
|
||||
stoppable: task.backgrounded
|
||||
}
|
||||
}
|
||||
|
||||
export type ClaudeTaskFacts = {
|
||||
toolName?: string
|
||||
lastMessage?: string
|
||||
@@ -57,6 +118,9 @@ export function withClaudeChildWorkOwners(
|
||||
return evidence
|
||||
}
|
||||
const owned = (child: AgentChildWorkLiveObservation): AgentChildWorkLiveObservation => {
|
||||
if (child.ownerId !== undefined) {
|
||||
return child
|
||||
}
|
||||
const ownerId = child.handle.runId === undefined ? null : ownerOf(child.handle.runId)
|
||||
return ownerId !== null && ownerId !== child.handle.id ? { ...child, ownerId } : child
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { expect, it } from 'vitest'
|
||||
import { ClaudeChildWorkDecoder } from './claude-child-work-decoder'
|
||||
import { createAgentStatusStore } from '../../shared/agent-status/store/agent-status-store'
|
||||
import { createAgentChildWorkAdmission } from '../../shared/agent-status/child-work/agent-status-child-work-admission'
|
||||
import { reconcileAgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-reconciliation'
|
||||
import { parent } from './claude-child-work-producer-harness.test-fixture'
|
||||
|
||||
it('emits only new or changed roster facts at10 and100 live tasks', () => {
|
||||
for (const count of [10, 100]) {
|
||||
const decoder = new ClaudeChildWorkDecoder()
|
||||
const store = createAgentStatusStore({ epoch: 'roster-perf', mode: 'authority' })
|
||||
store.applyMutation({ parent: { subject: parent } })
|
||||
let minted = 0
|
||||
const admission = createAgentChildWorkAdmission(store, {
|
||||
mintChildWorkId: () => `child-${++minted}`
|
||||
})
|
||||
let clock = 1_700_000_000_000
|
||||
let rosterEdges = 0
|
||||
let rosterWrites = 0
|
||||
const feed = (message: Record<string, unknown>, rosterBound = 0) => {
|
||||
decoder.observe({ type: 'system', ...message })
|
||||
const evidence = decoder.drain(++clock)
|
||||
const before = store.getSnapshot().revision
|
||||
reconcileAgentChildWorkEvidence({ store, admission, parent, provider: 'claude', evidence })
|
||||
const writes = store.getSnapshot().revision - before
|
||||
if (message.subtype === 'background_tasks_changed') {
|
||||
const live = evidence.filter((edge) => edge.type === 'live').length
|
||||
expect(live).toBeLessThanOrEqual(rosterBound)
|
||||
expect(writes).toBeLessThanOrEqual(rosterBound)
|
||||
rosterEdges += live
|
||||
rosterWrites += writes
|
||||
}
|
||||
}
|
||||
const owner = {
|
||||
task_id: 'owner',
|
||||
task_type: 'local_agent',
|
||||
tool_use_id: 'tool-owner',
|
||||
is_backgrounded: true
|
||||
}
|
||||
feed({ subtype: 'task_started', ...owner })
|
||||
let shellOwner = 'owner'
|
||||
const shell = (id: number) => ({
|
||||
task_id: `shell-${id}`,
|
||||
task_type: 'local_bash',
|
||||
description: `shell${id}`,
|
||||
parent_task_id: shellOwner
|
||||
})
|
||||
const live: number[] = []
|
||||
for (let id = 0; id < count; id++) {
|
||||
live.push(id)
|
||||
const roster = { subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] }
|
||||
// Only one task is newly present; unchanged replacement rosters need no host writes.
|
||||
feed(roster, 1)
|
||||
feed({
|
||||
subtype: 'task_started',
|
||||
...shell(id),
|
||||
tool_use_id: `tool-${id}`,
|
||||
is_backgrounded: true
|
||||
})
|
||||
feed(roster)
|
||||
}
|
||||
// The introductions above need at most one edge/write each, independent of full-roster size.
|
||||
expect(rosterEdges).toBeLessThanOrEqual(count)
|
||||
expect(rosterWrites).toBeLessThanOrEqual(count)
|
||||
rosterEdges = 0
|
||||
rosterWrites = 0
|
||||
feed({ subtype: 'task_started', ...owner, task_id: 'owner-second', tool_use_id: 'tool-second' })
|
||||
shellOwner = 'owner-second'
|
||||
// A real owner change invalidates exactly the affected children, then its duplicate invalidates none.
|
||||
feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) }, count)
|
||||
feed({ subtype: 'background_tasks_changed', tasks: live.map(shell) })
|
||||
for (let id = 0; id < count; id++) {
|
||||
feed({
|
||||
subtype: 'task_notification',
|
||||
task_id: `shell-${id}`,
|
||||
tool_use_id: `tool-${id}`,
|
||||
status: 'completed'
|
||||
})
|
||||
live.shift()
|
||||
feed({ subtype: 'background_tasks_changed', tasks: [owner, ...live.map(shell)] })
|
||||
}
|
||||
// N introductions require at most N live edges and N store writes, independent of roster size.
|
||||
expect(rosterEdges).toBeLessThanOrEqual(count)
|
||||
expect(rosterWrites).toBeLessThanOrEqual(count)
|
||||
expect(store.getChildren(parent).filter((child) => child.kind === 'command')).toHaveLength(
|
||||
count
|
||||
)
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,112 @@
|
||||
import { expect, it, vi } from 'vitest'
|
||||
import { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery'
|
||||
import { bindClaudeJournalReadingControl } from './structured/journal/claude-structured-session-journal-control'
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionReadingControl
|
||||
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
|
||||
function unboundSink() {
|
||||
let notify: (() => void) | undefined
|
||||
let control: StructuredAgentSessionReadingControl | undefined
|
||||
let bound = false
|
||||
const sink: StructuredAgentSessionEventSink = {
|
||||
appendItem: () => {},
|
||||
appendTombstone: () => {},
|
||||
publish: () => {},
|
||||
onJournalBound: (listener) => {
|
||||
notify = listener
|
||||
return () => {
|
||||
notify = undefined
|
||||
}
|
||||
},
|
||||
journalLinkage: () =>
|
||||
bound
|
||||
? {
|
||||
epoch: 'test',
|
||||
visitItemsWithLinkage: () => {},
|
||||
threadGoal: () => null,
|
||||
threadGoalSource: () => ({ goal: null, row: null })
|
||||
}
|
||||
: null,
|
||||
bindReadingControl: (next) => {
|
||||
control = next
|
||||
return () => {}
|
||||
}
|
||||
}
|
||||
return {
|
||||
sink,
|
||||
bind: () => {
|
||||
bound = true
|
||||
notify?.()
|
||||
},
|
||||
pressure: (paused: boolean) => control?.[paused ? 'pauseReading' : 'resumeReading']()
|
||||
}
|
||||
}
|
||||
|
||||
it('holds ordered interpretation until binding while preserving independent sink pressure', () => {
|
||||
const state = unboundSink()
|
||||
let published = false
|
||||
const delivery = new ClaudeJournalBoundDelivery(state.sink, () => published)
|
||||
const connection = { pauseReading: vi.fn(), resumeReading: vi.fn() }
|
||||
bindClaudeJournalReadingControl(state.sink, connection, null, delivery)
|
||||
const observed: string[] = []
|
||||
delivery.deliver(() => {
|
||||
observed.push('start')
|
||||
delivery.deliver(() => observed.push('later'))
|
||||
})
|
||||
delivery.deliver(() => observed.push('terminal'))
|
||||
published = true
|
||||
delivery.flush()
|
||||
state.pressure(true)
|
||||
expect(observed).toEqual([])
|
||||
state.bind()
|
||||
expect(observed).toEqual(['start', 'terminal', 'later'])
|
||||
expect(connection.resumeReading).not.toHaveBeenCalled()
|
||||
state.pressure(false)
|
||||
expect(connection.resumeReading).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('terminates the uncommitted prefix on disposal and ignores a late binding', () => {
|
||||
const state = unboundSink()
|
||||
const delivery = new ClaudeJournalBoundDelivery(state.sink)
|
||||
const interpret = vi.fn()
|
||||
delivery.deliver(interpret)
|
||||
delivery.dispose()
|
||||
state.bind()
|
||||
delivery.deliver(interpret)
|
||||
expect(interpret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails a bounded unbound prefix instead of silently losing or replaying observations', () => {
|
||||
const state = unboundSink()
|
||||
const delivery = new ClaudeJournalBoundDelivery(state.sink)
|
||||
const failure = vi.fn()
|
||||
const interpret = vi.fn()
|
||||
delivery.onFailure = failure
|
||||
const payload = 'x'.repeat(1024 * 1024)
|
||||
expect(() => {
|
||||
for (let index = 0; index < 33; index++) {
|
||||
delivery.deliver(interpret, payload)
|
||||
}
|
||||
}).toThrow('capacity exceeded')
|
||||
state.bind()
|
||||
expect(failure).toHaveBeenCalledOnce()
|
||||
expect(interpret).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports binding interpretation failure through its owning failure path', () => {
|
||||
const state = unboundSink()
|
||||
const delivery = new ClaudeJournalBoundDelivery(state.sink)
|
||||
const failure = vi.fn()
|
||||
delivery.onFailure = failure
|
||||
const error = new Error('invalid saved identity')
|
||||
delivery.deliver(() => {
|
||||
throw error
|
||||
})
|
||||
const later = vi.fn()
|
||||
delivery.deliver(later)
|
||||
expect(() => state.bind()).not.toThrow()
|
||||
expect(failure).toHaveBeenCalledWith(error)
|
||||
expect(later).not.toHaveBeenCalled()
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import type {
|
||||
StructuredAgentSessionEventSink,
|
||||
StructuredAgentSessionReadingControl
|
||||
} from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
|
||||
/** Own provider observations until their saved identity input is available. */
|
||||
export class ClaudeJournalBoundDelivery {
|
||||
private pending: ({ run: () => void; bytes: number } | undefined)[] = []
|
||||
private entries = 0
|
||||
private bytes = 0
|
||||
private draining = false
|
||||
private closed = false
|
||||
private unsubscribe?: () => void
|
||||
private control?: StructuredAgentSessionReadingControl
|
||||
private paused = false
|
||||
onFailure?: (error: Error) => void
|
||||
|
||||
constructor(
|
||||
private sink?: StructuredAgentSessionEventSink,
|
||||
private readonly published: () => boolean = () => true
|
||||
) {
|
||||
this.bind(sink)
|
||||
}
|
||||
|
||||
bind(sink: StructuredAgentSessionEventSink | undefined): void {
|
||||
this.unsubscribe?.()
|
||||
this.sink = sink
|
||||
this.unsubscribe = sink?.onJournalBound?.(() => this.flush())
|
||||
}
|
||||
|
||||
get ready(): boolean {
|
||||
return (
|
||||
!this.closed &&
|
||||
this.published() &&
|
||||
(!this.sink?.onJournalBound || this.sink.journalLinkage?.() !== null)
|
||||
)
|
||||
}
|
||||
|
||||
bindReadingControl(control: StructuredAgentSessionReadingControl): () => void {
|
||||
this.control = control
|
||||
if (this.paused) {
|
||||
control.pauseReading()
|
||||
}
|
||||
return () => {
|
||||
if (this.control === control) {
|
||||
this.control = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
deliver(run: () => void, payload?: unknown): void {
|
||||
if (this.closed) {
|
||||
return
|
||||
}
|
||||
if (this.ready && !this.draining) {
|
||||
run()
|
||||
return
|
||||
}
|
||||
const bytes = Buffer.byteLength(JSON.stringify(payload ?? null), 'utf8') + 64
|
||||
if (this.entries >= 1_024 || this.bytes + bytes > 32 * 1024 * 1024) {
|
||||
const error = new Error('Claude event delivery capacity exceeded before journal binding')
|
||||
this.dispose()
|
||||
this.onFailure?.(error)
|
||||
throw error
|
||||
}
|
||||
this.pending.push({ run, bytes })
|
||||
this.entries++
|
||||
this.bytes += bytes
|
||||
this.updateReading()
|
||||
}
|
||||
|
||||
interpret<T extends { type: string }>(event: T, handle: (event: T) => void): void {
|
||||
if (event.type === 'ended' || event.type === 'retiring') {
|
||||
this.dispose()
|
||||
handle(event)
|
||||
} else if (this.ready) {
|
||||
handle(event)
|
||||
} else {
|
||||
this.deliver(() => handle(event), event)
|
||||
}
|
||||
}
|
||||
|
||||
flush(): void {
|
||||
if (!this.ready || this.draining) {
|
||||
this.updateReading()
|
||||
return
|
||||
}
|
||||
this.draining = true
|
||||
try {
|
||||
while (this.pending.length && !this.closed) {
|
||||
const prefix = this.pending
|
||||
this.pending = []
|
||||
for (let index = 0; index < prefix.length; index++) {
|
||||
if (this.closed) {
|
||||
break
|
||||
}
|
||||
const entry = prefix[index]!
|
||||
prefix[index] = undefined
|
||||
this.entries--
|
||||
this.bytes -= entry.bytes
|
||||
entry.run()
|
||||
}
|
||||
}
|
||||
} catch (cause) {
|
||||
this.dispose()
|
||||
const error = cause instanceof Error ? cause : new Error(String(cause))
|
||||
if (!this.onFailure) {
|
||||
throw error
|
||||
}
|
||||
this.onFailure(error)
|
||||
} finally {
|
||||
this.draining = false
|
||||
this.updateReading()
|
||||
}
|
||||
}
|
||||
|
||||
/** Retirement ends uncommitted delivery; it must never replay into a disposed translator. */
|
||||
dispose(): void {
|
||||
this.closed = true
|
||||
this.pending = []
|
||||
this.entries = 0
|
||||
this.bytes = 0
|
||||
this.unsubscribe?.()
|
||||
this.unsubscribe = undefined
|
||||
this.updateReading()
|
||||
}
|
||||
|
||||
private updateReading(): void {
|
||||
const paused = !this.closed && this.published() && !this.ready
|
||||
if (paused !== this.paused) {
|
||||
this.paused = paused
|
||||
this.control?.[paused ? 'pauseReading' : 'resumeReading']()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import type { ClaudeJournalBoundDelivery } from './claude-journal-bound-delivery'
|
||||
import type { AgentSessionContextReport } from '../../shared/agent-session/agent-session-context-usage'
|
||||
import type { AgentJournalTurnScope } from '../../shared/agent-session/journal/agent-session-journal-turn-scope'
|
||||
import type {
|
||||
@@ -16,6 +18,7 @@ import type { AgentSessionAccountKind } from '../../shared/agent-session/agent-s
|
||||
|
||||
export type ClaudeJournalTranslatorDeps = {
|
||||
sink: StructuredAgentSessionEventSink
|
||||
delivery?: ClaudeJournalBoundDelivery
|
||||
bindPromptItemId?: (journalItemId: string, promptKey: string) => void
|
||||
coalesceMs?: number
|
||||
schedule?: AgentSessionDeltaCoalescerDeps['schedule']
|
||||
@@ -29,6 +32,7 @@ export type ClaudeJournalTranslatorDeps = {
|
||||
}
|
||||
|
||||
export type ClaudeJournalTranslator = {
|
||||
readonly taskInvocations: ClaudeTaskInvocations
|
||||
handle: (event: ClaudeStructuredSessionEvent) => void
|
||||
journalPrompts: Pick<
|
||||
ClaudeJournalPrompts,
|
||||
@@ -45,6 +49,7 @@ export type ClaudeJournalTranslator = {
|
||||
readonly openTurnInLiveProviderCycle: boolean
|
||||
readonly openTurnHasInputWork: boolean
|
||||
flush: () => void
|
||||
childTaskParent?: (taskId: string, run?: string) => string | undefined
|
||||
childToolOwner?: ClaudeChildToolQueries['childToolOwner']
|
||||
childActivity?: ClaudeChildToolQueries['childActivity']
|
||||
retryPendingTaskRows?: () => StructuredAgentSessionSinkAdmission
|
||||
|
||||
@@ -196,7 +196,10 @@ export function journalClaudeMessage(
|
||||
tool.name === 'Monitor' &&
|
||||
ctx.toolOrigins.has(result.toolUseId)
|
||||
) {
|
||||
ctx.backgroundTasks.observeMonitorToolResult(claudeRecord(message.tool_use_result)?.taskId)
|
||||
ctx.backgroundTasks.observeMonitorToolResult(
|
||||
claudeRecord(message.tool_use_result)?.taskId,
|
||||
result.toolUseId
|
||||
)
|
||||
}
|
||||
ctx.tools.delete(result.toolUseId)
|
||||
changed = true
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// CLI 2.1.319, isolated real run: parent Stop, live child roster, then separate child Stop; IDs/paths sanitized.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import type { CapturedFrame } from './claude-captured-frame-builders.test-fixture'
|
||||
|
||||
export const PARENT_TASK_STOP: CapturedFrame[] = readFileSync(
|
||||
new URL('./__fixtures__/claude-parent-task-stop-2.1.319.jsonl', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((line) => JSON.parse(line))
|
||||
@@ -0,0 +1,785 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import {
|
||||
producer,
|
||||
frame,
|
||||
system,
|
||||
toolUse,
|
||||
toolResult
|
||||
} from './claude-child-work-producer-harness.test-fixture'
|
||||
import { createTrackedJournalOpener } from '../native-chat/agent-session-journal/store-lifecycle/journal-host-database-test-support'
|
||||
import { createDeferredStructuredAgentSessionEventSink } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-event-sink'
|
||||
import { createClaudeJournalTranslator } from './structured/journal/claude-structured-journal-translation'
|
||||
import { testEventSinkLogging } from '../native-chat/agent-session-wire/host/testing/structured-agent-session-logger-test-support'
|
||||
import { claudeProviderHandle } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding'
|
||||
import {
|
||||
claudeBackgroundTaskBody,
|
||||
claudeBackgroundTaskIdentity
|
||||
} from './claude-background-task-row-journal'
|
||||
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import {
|
||||
adapterAtPublishFor,
|
||||
fakeClaude,
|
||||
identityFor
|
||||
} from './structured/claude-structured-session-test-support'
|
||||
import type { AgentChildWorkEvidence } from '../../shared/agent-status/child-work/agent-status-child-work-evidence'
|
||||
import { ClaudeSubagentIdentities } from './claude-subagent-identities'
|
||||
import { ClaudeJournaledSubagents } from './claude-subagent-journaled-identities'
|
||||
|
||||
const journals = createTrackedJournalOpener()
|
||||
const cleanup: string[] = []
|
||||
afterEach(async () => {
|
||||
await journals.closeAll()
|
||||
for (const path of cleanup.splice(0)) {
|
||||
await rm(path, { recursive: true, force: true })
|
||||
}
|
||||
})
|
||||
|
||||
it('retains explicit ambient and skip-transcript exclusion when roster omits those optional flags', async () => {
|
||||
for (const flag of ['ambient', 'skip_transcript']) {
|
||||
const run = await producer()
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'excluded',
|
||||
task_type: 'local_bash',
|
||||
parent_task_id: 'owner',
|
||||
is_backgrounded: true,
|
||||
tool_use_id: 'tool-old',
|
||||
[flag]: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('background_tasks_changed', {
|
||||
tasks: [{ task_id: 'excluded', task_type: 'local_bash', parent_task_id: 'owner' }]
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_updated', {
|
||||
task_id: 'excluded',
|
||||
patch: { status: 'running', is_backgrounded: true, description: 'Excluded shell' }
|
||||
})
|
||||
)
|
||||
expect.soft(run.records(), flag).toEqual([])
|
||||
expect
|
||||
.soft(
|
||||
[...run.journalItems.values()].filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some((block) => block.type === 'background-task')
|
||||
),
|
||||
flag
|
||||
)
|
||||
.toEqual([])
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'excluded',
|
||||
tool_use_id: 'tool-old',
|
||||
status: 'stopped'
|
||||
})
|
||||
)
|
||||
run.send(toolUse('tool-new', 'Bash', { command: 'sleep 1', run_in_background: true }))
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'excluded',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-new',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
expect(run.records().find((row) => row.kind === 'command')).toMatchObject({
|
||||
membership: 'live'
|
||||
})
|
||||
run.send(
|
||||
system('task_progress', {
|
||||
task_id: 'excluded',
|
||||
tool_use_id: 'tool-pending',
|
||||
parent_task_id: 'pending-owner',
|
||||
[flag]: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'excluded',
|
||||
tool_use_id: 'tool-new',
|
||||
status: 'stopped'
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'excluded',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-pending',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
expect(run.records().filter((row) => row.membership === 'live')).toEqual([])
|
||||
expect(
|
||||
[...run.journalItems.values()].some(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.parentToolUseId === 'tool-pending'
|
||||
)
|
||||
)
|
||||
).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('uses the matching durable generation ownership when an earlier run receives a terminal revision', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-parent-review-codex-'))
|
||||
cleanup.push(root)
|
||||
const journal = await journals.open({
|
||||
identity: {
|
||||
sessionId: 'orca-session',
|
||||
workspaceId: 'workspace-1',
|
||||
hostId: 'local',
|
||||
agent: 'claude',
|
||||
providerHandle: claudeProviderHandle('claude-session', null)
|
||||
},
|
||||
now: () => 9000,
|
||||
stateDirectory: root
|
||||
})
|
||||
for (const [generation, tool, owner] of [
|
||||
[1, 'tool-first', 'owner-first'],
|
||||
[2, 'tool-second', 'owner-second'],
|
||||
[3, 'tool-root', undefined]
|
||||
] as const) {
|
||||
await journal.appendItem(
|
||||
claudeBackgroundTaskIdentity('reused', generation),
|
||||
claudeBackgroundTaskBody({
|
||||
type: 'background-task',
|
||||
taskId: 'reused',
|
||||
kind: 'command',
|
||||
label: 'sleep',
|
||||
parentToolUseId: tool,
|
||||
state: 'unverifiable',
|
||||
startedAt: 1
|
||||
}),
|
||||
{
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE,
|
||||
...(owner
|
||||
? {
|
||||
agentId: 'reused',
|
||||
parentAgentId: owner,
|
||||
producerKind: 'background' as const,
|
||||
providerParentRef: tool
|
||||
}
|
||||
: {})
|
||||
}
|
||||
)
|
||||
}
|
||||
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
|
||||
deferred.bind({ journal, fence: 1, publish: () => {} })
|
||||
const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 })
|
||||
translator.handle({
|
||||
type: 'message',
|
||||
sessionId: 'orca-session',
|
||||
message: {
|
||||
type: 'system',
|
||||
subtype: 'task_notification',
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-first',
|
||||
session_id: 'claude-session',
|
||||
uuid: 'historical-owned-completion',
|
||||
status: 'completed'
|
||||
}
|
||||
})
|
||||
expect(await deferred.drained()).toEqual({ ok: true })
|
||||
expect(journal.runningTurn()).toBeNull()
|
||||
const prior = journal
|
||||
.snapshot()
|
||||
.items.find(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.parentToolUseId === 'tool-first'
|
||||
)
|
||||
)
|
||||
translator.handle({
|
||||
type: 'message',
|
||||
sessionId: 'orca-session',
|
||||
message: {
|
||||
type: 'system',
|
||||
subtype: 'task_notification',
|
||||
task_id: 'reused',
|
||||
status: 'completed'
|
||||
}
|
||||
})
|
||||
expect(await deferred.drained()).toEqual({ ok: true })
|
||||
const rootRow = journal
|
||||
.snapshot()
|
||||
.items.find(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.parentToolUseId === 'tool-root'
|
||||
)
|
||||
)
|
||||
expect(rootRow?.agentId).toBeUndefined()
|
||||
expect(rootRow?.body.kind === 'message' ? rootRow.body.blocks : []).toContainEqual(
|
||||
expect.objectContaining({ taskId: 'reused', parentToolUseId: 'tool-root', state: 'done' })
|
||||
)
|
||||
translator.handle({
|
||||
type: 'message',
|
||||
sessionId: 'orca-session',
|
||||
message: system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-first',
|
||||
parent_task_id: 'owner-first',
|
||||
is_backgrounded: true
|
||||
})
|
||||
})
|
||||
expect(await deferred.drained()).toEqual({ ok: true })
|
||||
const oldBody = journal
|
||||
.snapshot()
|
||||
.items.find((row) => row.providerParentRef === 'tool-first')?.body
|
||||
expect(oldBody?.kind === 'message' ? oldBody.blocks : []).toContainEqual(
|
||||
expect.objectContaining({ parentToolUseId: 'tool-first', state: 'done' })
|
||||
)
|
||||
translator.dispose()
|
||||
deferred.close()
|
||||
const queued = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
|
||||
const pending = createClaudeJournalTranslator({ sink: queued.sink, coalesceMs: 0 })
|
||||
const feed = (subtype: string, fields: Record<string, unknown>) =>
|
||||
pending.handle({
|
||||
type: 'message',
|
||||
sessionId: 'orca-session',
|
||||
message: system(subtype, fields)
|
||||
})
|
||||
feed('task_started', {
|
||||
task_id: 'queued',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'queued-old',
|
||||
parent_task_id: 'owner-first',
|
||||
is_backgrounded: true
|
||||
})
|
||||
feed('task_notification', { task_id: 'queued', tool_use_id: 'queued-old', status: 'stopped' })
|
||||
feed('task_progress', {
|
||||
task_id: 'queued',
|
||||
tool_use_id: 'queued-new',
|
||||
description: 'New operation before announcement'
|
||||
})
|
||||
feed('task_started', {
|
||||
task_id: 'queued',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'queued-new',
|
||||
parent_task_id: 'owner-second',
|
||||
is_backgrounded: true
|
||||
})
|
||||
feed('task_updated', {
|
||||
task_id: 'queued',
|
||||
tool_use_id: 'queued-old',
|
||||
patch: { status: 'completed' }
|
||||
})
|
||||
feed('task_progress', {
|
||||
task_id: 'queued',
|
||||
tool_use_id: 'queued-old',
|
||||
description: 'Old operation'
|
||||
})
|
||||
queued.bind({ journal, fence: 1, publish: () => {} })
|
||||
expect(await queued.drained()).toEqual({ ok: true })
|
||||
const queuedRows = journal
|
||||
.snapshot()
|
||||
.items.filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.taskId === 'queued'
|
||||
)
|
||||
)
|
||||
expect(queuedRows).toHaveLength(2)
|
||||
const current = queuedRows.find((row) => row.providerParentRef === 'queued-new')
|
||||
expect(current).toMatchObject({ parentAgentId: 'owner-second' })
|
||||
expect(current?.body.kind === 'message' ? current.body.blocks : []).toContainEqual(
|
||||
expect.objectContaining({ parentToolUseId: 'queued-new', state: 'working' })
|
||||
)
|
||||
pending.dispose()
|
||||
queued.close()
|
||||
expect(prior).toMatchObject({ parentAgentId: 'owner-first', providerParentRef: 'tool-first' })
|
||||
})
|
||||
|
||||
it('advances a journaled nested agent attempt rather than replacing it with the parent placeholder', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-nested-parent-recovery-'))
|
||||
cleanup.push(root)
|
||||
const journal = await journals.open({
|
||||
identity: {
|
||||
sessionId: 'orca-session',
|
||||
workspaceId: 'workspace-1',
|
||||
hostId: 'local',
|
||||
agent: 'claude',
|
||||
providerHandle: claudeProviderHandle('claude-session', null)
|
||||
},
|
||||
now: () => 9000,
|
||||
stateDirectory: root
|
||||
})
|
||||
await journal.appendItem(
|
||||
{ provider: 'claude', sessionId: 'claude-session', uuid: 'saved-attempt' },
|
||||
{ kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'previous attempt' }] },
|
||||
{
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE,
|
||||
agentId: 'nested',
|
||||
parentAgentId: 'owner',
|
||||
producerKind: 'agent',
|
||||
providerParentRef: 'tool-second',
|
||||
attempt: 2
|
||||
}
|
||||
)
|
||||
const journaled = new ClaudeJournaledSubagents(() => journal)
|
||||
const identities = new ClaudeSubagentIdentities({ journaled })
|
||||
identities.observeSystemFrame({
|
||||
type: 'system',
|
||||
subtype: 'background_tasks_changed',
|
||||
tasks: [{ task_id: 'nested', task_type: 'local_agent', parent_task_id: 'owner' }]
|
||||
})
|
||||
identities.observeSystemFrame({
|
||||
type: 'system',
|
||||
subtype: 'task_started',
|
||||
task_id: 'nested',
|
||||
tool_use_id: 'tool-third',
|
||||
task_type: 'local_agent',
|
||||
parent_task_id: 'owner'
|
||||
})
|
||||
expect(identities.linkage.settledLinkageFor('tool-third')).toMatchObject({
|
||||
kind: 'linked',
|
||||
linkage: { attempt: 3 }
|
||||
})
|
||||
})
|
||||
|
||||
it.each(['notification', 'killed', 'failed'])(
|
||||
'keeps distinct shell invocations isolated after %s',
|
||||
async (ending) => {
|
||||
const run = await producer()
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'owner',
|
||||
task_type: 'local_agent',
|
||||
tool_use_id: 'spawn-owner',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-first',
|
||||
parent_task_id: 'owner',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
ending === 'notification'
|
||||
? system('task_notification', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-first',
|
||||
status: 'stopped'
|
||||
})
|
||||
: system('task_updated', { task_id: 'reused', patch: { status: ending } })
|
||||
)
|
||||
run.send(
|
||||
system('task_progress', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-root',
|
||||
description: 'New operation before announcement'
|
||||
})
|
||||
)
|
||||
expect(run.records().find((row) => row.kind === 'command')).toMatchObject({
|
||||
membership: 'settled',
|
||||
stoppable: false
|
||||
})
|
||||
expect(
|
||||
[...run.journalItems.values()].filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some((block) => block.type === 'background-task')
|
||||
)
|
||||
).toHaveLength(1)
|
||||
run.send(toolUse('tool-root', 'Bash', { command: 'sleep 1', run_in_background: true }))
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-root',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_updated', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-first',
|
||||
patch: { status: 'completed' }
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_progress', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-first',
|
||||
description: 'Old operation'
|
||||
})
|
||||
)
|
||||
const newer = [...run.journalItems.values()].find(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.parentToolUseId === 'tool-root'
|
||||
)
|
||||
)
|
||||
expect.soft(newer).toBeDefined()
|
||||
expect.soft(newer?.agentId).toBeUndefined()
|
||||
const owner = run.records().find((row) => row.kind === 'agent')
|
||||
const child = run.records().find((row) => row.kind === 'command')
|
||||
expect(child?.parentChildWorkId).not.toBe(owner?.childWorkId)
|
||||
expect(child).toMatchObject({ membership: 'live', stoppable: true })
|
||||
expect(JSON.stringify(child)).not.toContain('Old operation')
|
||||
expect(newer?.body.kind === 'message' ? newer.body.blocks : []).toContainEqual(
|
||||
expect.objectContaining({ parentToolUseId: 'tool-root', state: 'working' })
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
it.each([false, true])(
|
||||
'keeps Monitor invocation reports out of the transcript, reused ID: %s',
|
||||
async (reused) => {
|
||||
const run = await producer()
|
||||
if (reused) {
|
||||
run.send(toolUse('tool-old', 'Bash', { command: 'sleep 1', run_in_background: true }))
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'monitor-task',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-old',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'monitor-task',
|
||||
tool_use_id: 'tool-old',
|
||||
status: 'completed'
|
||||
})
|
||||
)
|
||||
}
|
||||
run.send(toolUse('tool-monitor', 'Monitor', { command: 'watch' }))
|
||||
run.send({
|
||||
...toolResult('tool-monitor', 'Started'),
|
||||
tool_use_result: { taskId: 'monitor-task' }
|
||||
})
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'monitor-task',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-monitor',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('background_tasks_changed', {
|
||||
tasks: [{ task_id: 'monitor-task', task_type: 'local_bash', parent_task_id: 'owner' }]
|
||||
})
|
||||
)
|
||||
expect(
|
||||
[...run.journalItems.values()].filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some((block) => block.type === 'background-task')
|
||||
)
|
||||
).toHaveLength(reused ? 1 : 0)
|
||||
expect(run.records().some((row) => row.membership === 'live')).toBe(true)
|
||||
}
|
||||
)
|
||||
|
||||
it('retains pending ownership and terminal evidence without granting a partial frame live authority', async () => {
|
||||
const run = await producer()
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-old',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_progress', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-owned',
|
||||
parent_task_id: 'owner'
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-old',
|
||||
status: 'stopped'
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-owned',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
expect(run.records().find((row) => row.kind === 'command')).toMatchObject({
|
||||
membership: 'live',
|
||||
stoppable: true
|
||||
})
|
||||
expect(
|
||||
[...run.journalItems.values()].find(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.parentToolUseId === 'tool-owned'
|
||||
)
|
||||
)
|
||||
).toMatchObject({ agentId: 'reused' })
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-stopped-before-start',
|
||||
status: 'stopped'
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'reused',
|
||||
tool_use_id: 'tool-owned',
|
||||
status: 'stopped'
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'reused',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'tool-stopped-before-start',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
expect(run.records().filter((row) => row.membership === 'live')).toEqual([])
|
||||
const stoppedBody = [...run.journalItems.values()].find(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) =>
|
||||
block.type === 'background-task' && block.parentToolUseId === 'tool-stopped-before-start'
|
||||
)
|
||||
)?.body
|
||||
expect(stoppedBody?.kind === 'message' ? stoppedBody.blocks : []).toContainEqual(
|
||||
expect.objectContaining({ parentToolUseId: 'tool-stopped-before-start', state: 'idle' })
|
||||
)
|
||||
})
|
||||
|
||||
it.each(['alias', 'no-alias', 'partial-alias', 'known-terminal'])(
|
||||
'admits a resumed agent only when the terminal did not identify that invocation: %s',
|
||||
async (shape) => {
|
||||
const run = await producer()
|
||||
run.send(
|
||||
system('task_notification', {
|
||||
task_id: 'owner',
|
||||
status: 'stopped',
|
||||
...(shape === 'known-terminal' ? { tool_use_id: 'spawn-owner' } : {})
|
||||
})
|
||||
)
|
||||
if (shape === 'partial-alias') {
|
||||
run.send(system('task_progress', { task_id: 'owner', tool_use_id: 'spawn-owner' }))
|
||||
}
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'owner',
|
||||
task_type: 'local_agent',
|
||||
is_backgrounded: true,
|
||||
...(shape === 'no-alias' ? {} : { tool_use_id: 'spawn-owner' })
|
||||
})
|
||||
)
|
||||
run.send(
|
||||
system('task_started', {
|
||||
task_id: 'shell',
|
||||
task_type: 'local_bash',
|
||||
tool_use_id: 'shell-tool',
|
||||
parent_task_id: 'owner',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
const owner = run.records().find((row) => row.kind === 'agent')
|
||||
const shell = run.records().find((row) => row.kind === 'command')
|
||||
if (shape === 'known-terminal') {
|
||||
expect(owner?.membership).not.toBe('live')
|
||||
} else {
|
||||
expect(owner).toMatchObject({ membership: 'live', stoppable: true })
|
||||
expect(shell).toMatchObject({
|
||||
membership: 'live',
|
||||
stoppable: true,
|
||||
parentChildWorkId: owner?.childWorkId
|
||||
})
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('releases an alias-less roster against reopened ownership on binding without another provider frame', async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), 'orca-parent-binding-'))
|
||||
cleanup.push(root)
|
||||
const identity = identityFor()
|
||||
const open = () => journals.open({ identity, now: () => 9000, stateDirectory: root })
|
||||
let journal = await open()
|
||||
for (const id of ['saved-shell', 'saved-only']) {
|
||||
await journal.appendItem(
|
||||
claudeBackgroundTaskIdentity(id, 1),
|
||||
claudeBackgroundTaskBody({
|
||||
type: 'background-task',
|
||||
taskId: id,
|
||||
kind: 'command',
|
||||
label: 'sleep',
|
||||
parentToolUseId: 'saved-tool',
|
||||
state: 'unverifiable',
|
||||
startedAt: 1
|
||||
}),
|
||||
{
|
||||
fence: 1,
|
||||
turnScope: AGENT_JOURNAL_THREAD_SCOPE,
|
||||
agentId: id,
|
||||
parentAgentId: 'saved-owner',
|
||||
producerKind: 'background',
|
||||
providerParentRef: 'saved-tool'
|
||||
}
|
||||
)
|
||||
}
|
||||
const originalId = journal.snapshot().items[0]!.itemId
|
||||
await journals.closeAll()
|
||||
journal = await open()
|
||||
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
|
||||
deferred.sink.appendItem(
|
||||
{ provider: 'claude', sessionId: 'saved-session', uuid: 'before-bind' },
|
||||
{ kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Earlier queued write' }] },
|
||||
{ turnScope: AGENT_JOURNAL_THREAD_SCOPE }
|
||||
)
|
||||
const claude = fakeClaude()
|
||||
const evidence: AgentChildWorkEvidence[] = []
|
||||
const adapter = adapterAtPublishFor(
|
||||
claude,
|
||||
{},
|
||||
[],
|
||||
[],
|
||||
undefined,
|
||||
undefined,
|
||||
(_sessionId, batch) => evidence.push(...batch)
|
||||
)
|
||||
await adapter.acquire({ identity, fence: 1, spawnToken: 'binding-test', events: deferred.sink })
|
||||
const roster = () =>
|
||||
claude.connections[0]!.handlers.onMessage?.(
|
||||
system('background_tasks_changed', {
|
||||
tasks: [{ task_id: 'saved-shell', task_type: 'local_bash' }]
|
||||
})
|
||||
)
|
||||
roster()
|
||||
claude.connections[0]!.handlers.onMessage?.(
|
||||
frame({
|
||||
type: 'assistant',
|
||||
message: {
|
||||
id: 'held-assistant',
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', text: 'Later provider write' }]
|
||||
}
|
||||
})
|
||||
)
|
||||
expect(evidence.filter((edge) => edge.type === 'live')).toEqual([])
|
||||
deferred.bind({ journal, fence: 1, publish: () => {} })
|
||||
expect(await deferred.drained()).toEqual({ ok: true })
|
||||
expect(evidence).toContainEqual(
|
||||
expect.objectContaining({
|
||||
type: 'live',
|
||||
child: expect.objectContaining({
|
||||
ownerId: 'saved-owner',
|
||||
stoppable: true
|
||||
})
|
||||
})
|
||||
)
|
||||
const liveIds = evidence
|
||||
.filter((edge) => edge.type === 'live')
|
||||
.map((edge) => edge.child.handle.id)
|
||||
expect(liveIds).toContain('saved-shell')
|
||||
expect(liveIds).not.toContain('saved-only')
|
||||
const queuedMessages = journal
|
||||
.snapshot()
|
||||
.items.filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) =>
|
||||
block.type === 'text' &&
|
||||
(block.text === 'Earlier queued write' || block.text === 'Later provider write')
|
||||
)
|
||||
)
|
||||
expect(queuedMessages.map((row) => row.body)).toMatchObject([
|
||||
{ kind: 'message', blocks: [{ type: 'text', text: 'Earlier queued write' }] },
|
||||
{ kind: 'message', blocks: [{ type: 'text', text: 'Later provider write' }] }
|
||||
])
|
||||
expect(queuedMessages[0]!.sequence).toBeLessThan(queuedMessages[1]!.sequence)
|
||||
expect(journal.item(originalId)).toMatchObject({
|
||||
agentId: 'saved-shell',
|
||||
parentAgentId: 'saved-owner',
|
||||
providerParentRef: 'saved-tool'
|
||||
})
|
||||
expect(journal.item(originalId)?.body).toMatchObject({
|
||||
kind: 'message',
|
||||
blocks: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
taskId: 'saved-shell',
|
||||
parentToolUseId: 'saved-tool',
|
||||
state: 'working'
|
||||
})
|
||||
])
|
||||
})
|
||||
roster()
|
||||
expect(await deferred.drained()).toEqual({ ok: true })
|
||||
expect(
|
||||
journal
|
||||
.snapshot()
|
||||
.items.filter(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.taskId === 'saved-shell'
|
||||
)
|
||||
)
|
||||
).toHaveLength(1)
|
||||
expect(journal.snapshot().items.find((row) => row.agentId === 'saved-only')?.body).toMatchObject({
|
||||
kind: 'message',
|
||||
blocks: expect.arrayContaining([expect.objectContaining({ state: 'unverifiable' })])
|
||||
})
|
||||
const retired = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
|
||||
const replacement = adapterAtPublishFor(claude)
|
||||
await replacement.acquire({
|
||||
identity,
|
||||
fence: 1,
|
||||
spawnToken: 'retired-test',
|
||||
events: retired.sink
|
||||
})
|
||||
claude.connections[1]!.handlers.onMessage?.(
|
||||
system('task_started', {
|
||||
task_id: 'retired-shell',
|
||||
task_type: 'local_bash',
|
||||
is_backgrounded: true
|
||||
})
|
||||
)
|
||||
await replacement.releaseAcquisition({ sessionId: identity.sessionId })
|
||||
retired.bind({ journal, fence: 1, publish: () => {} })
|
||||
expect(await retired.drained()).toEqual({ ok: true })
|
||||
expect(
|
||||
journal
|
||||
.snapshot()
|
||||
.items.some(
|
||||
(row) =>
|
||||
row.body.kind === 'message' &&
|
||||
row.body.blocks.some(
|
||||
(block) => block.type === 'background-task' && block.taskId === 'retired-shell'
|
||||
)
|
||||
)
|
||||
).toBe(false)
|
||||
retired.close()
|
||||
await adapter.releaseAcquisition({ sessionId: identity.sessionId })
|
||||
deferred.close()
|
||||
})
|
||||
@@ -147,6 +147,20 @@ function processState(pid: number): 'running' | 'exited' {
|
||||
}
|
||||
|
||||
describe('Claude stream-json connection', () => {
|
||||
it('completes task Stop through the real SDK while semantic reading is paused', async () => {
|
||||
const scenario = scriptScenario([HOLD_OPEN])
|
||||
const connection = await open(launchFor(scenario))
|
||||
await connection.initializationResult()
|
||||
connection.pauseReading?.()
|
||||
await connection.stopTask('owned-shell')
|
||||
expect(scenario.readReport().controlRequests).toContainEqual(
|
||||
expect.objectContaining({
|
||||
request: expect.objectContaining({ subtype: 'stop_task', task_id: 'owned-shell' })
|
||||
})
|
||||
)
|
||||
connection.resumeReading?.()
|
||||
})
|
||||
|
||||
it('settles a send only once the frame reached the child, and replays reach onMessage', async () => {
|
||||
const replay = {
|
||||
type: 'user',
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClaudeTaskInvocations } from './claude-task-invocations'
|
||||
import { BoundedMap } from '../../shared/bounded-map'
|
||||
import { ClaudeSubagentIds } from './claude-subagent-id-aliases'
|
||||
import type { ClaudeJournaledSubagents } from './claude-subagent-journaled-identities'
|
||||
@@ -19,6 +20,7 @@ export type ClaudeSubagentIdentitiesDeps = {
|
||||
/** Resolve grandchildren through the child that journaled their spawn call. */
|
||||
childOwnerRefOf?: (toolUseId: string) => string | null
|
||||
journaled?: ClaudeJournaledSubagents
|
||||
taskInvocations?: ClaudeTaskInvocations
|
||||
}
|
||||
|
||||
export class ClaudeSubagentIdentities {
|
||||
@@ -26,9 +28,11 @@ export class ClaudeSubagentIdentities {
|
||||
private readonly known = new BoundedMap<string, KnownSubagent>({
|
||||
maxEntries: MAX_KNOWN_SUBAGENTS
|
||||
})
|
||||
readonly taskInvocations: ClaudeTaskInvocations
|
||||
readonly linkage: ClaudeSubagentLinkageSource & ClaudeAgentLinkageSource
|
||||
|
||||
constructor(private readonly deps: ClaudeSubagentIdentitiesDeps) {
|
||||
this.taskInvocations = deps.taskInvocations ?? new ClaudeTaskInvocations(deps.journaled)
|
||||
this.ids = new ClaudeSubagentIds(deps.journaled?.canonical)
|
||||
this.linkage = new ClaudeSubagentLinkage({
|
||||
ids: this.ids,
|
||||
@@ -39,11 +43,16 @@ export class ClaudeSubagentIdentities {
|
||||
},
|
||||
isForwardedParentTool: deps.isForwardedParentTool,
|
||||
childOwnerRefOf: deps.childOwnerRefOf,
|
||||
parentTaskOf: this.parentOf,
|
||||
spawnRefOf: (canonicalId) => this.known.get(canonicalId)?.run ?? null
|
||||
})
|
||||
}
|
||||
|
||||
parentOf = (id: string, run?: string): string | undefined =>
|
||||
this.taskInvocations.parentOf(id, run)
|
||||
|
||||
observeSystemFrame(message: Record<string, unknown>): boolean {
|
||||
this.taskInvocations.observe(message)
|
||||
const frame = readClaudeSubagentTaskFrame(message)
|
||||
if (!frame) {
|
||||
return false
|
||||
@@ -62,7 +71,10 @@ export class ClaudeSubagentIdentities {
|
||||
if (frame.toolUseId) {
|
||||
this.ids.alias(frame.toolUseId, frame.taskId)
|
||||
}
|
||||
if (frame.announcesSubagent) {
|
||||
if (
|
||||
frame.announcesSubagent &&
|
||||
this.taskInvocations.selection(message, frame.taskId)?.acceptsStart !== false
|
||||
) {
|
||||
this.announce(frame.taskId, frame.toolUseId)
|
||||
}
|
||||
return true
|
||||
|
||||
@@ -1,3 +1,10 @@
|
||||
import {
|
||||
indexClaudeBackgroundTask,
|
||||
selectClaudeBackgroundTask,
|
||||
type ClaudeBackgroundTaskIndex,
|
||||
type ClaudeBackgroundTaskDescriptor
|
||||
} from './claude-background-task-identity'
|
||||
import { isBackgroundTaskBlock } from '../../shared/native-chat/native-chat-types'
|
||||
import type { AgentJournalProducerLinkage } from '../../shared/agent-session/journal/agent-session-journal-types'
|
||||
import { namedSubagents } from '../../shared/native-chat/transcript/native-chat-subagent-items'
|
||||
import type { StructuredAgentSessionLinkageJournal } from '../native-chat/agent-session-wire/journal-ingress/structured-agent-session-journal-views'
|
||||
@@ -6,6 +13,8 @@ import { isBoundedClaudeTaskId } from './claude-background-task-tracker'
|
||||
type Reading = {
|
||||
canonicalByToolUse: Map<string, string>
|
||||
attemptByAgent: Map<string, number>
|
||||
parents: Map<string, Map<string | undefined, AgentJournalProducerLinkage>>
|
||||
backgrounds: Map<string, ClaudeBackgroundTaskIndex>
|
||||
subagents: Set<string>
|
||||
}
|
||||
|
||||
@@ -23,6 +32,15 @@ export class ClaudeJournaledSubagents {
|
||||
/** Zero means no journaled attempt. */
|
||||
attempt = (agentId: string): number => this.current()?.attemptByAgent.get(agentId) ?? 0
|
||||
|
||||
parent = (taskId: string, run?: string): string | undefined =>
|
||||
(run === undefined
|
||||
? [...(this.current()?.parents.get(taskId)?.values() ?? [])].at(-1)
|
||||
: this.current()?.parents.get(taskId)?.get(run)
|
||||
)?.parentAgentId
|
||||
|
||||
background = (taskId: string, run?: string): ClaudeBackgroundTaskDescriptor | undefined =>
|
||||
selectClaudeBackgroundTask(this.current()?.backgrounds.get(taskId), run)
|
||||
|
||||
isSubagent = (taskId: string): boolean => this.current()?.subagents.has(taskId) === true
|
||||
|
||||
private current(): Reading | null {
|
||||
@@ -43,9 +61,24 @@ function read(journal: StructuredAgentSessionLinkageJournal): Reading {
|
||||
const reading: Reading = {
|
||||
canonicalByToolUse: new Map(),
|
||||
attemptByAgent: new Map(),
|
||||
parents: new Map(),
|
||||
backgrounds: new Map(),
|
||||
subagents: new Set()
|
||||
}
|
||||
journal.visitItemsWithLinkage((_itemId, _sequence, body, linkage) => {
|
||||
journal.visitItemsWithLinkage((itemId, _sequence, body, linkage) => {
|
||||
if (linkage.agentId !== undefined && linkage.producerKind === 'agent') {
|
||||
const parents = reading.parents.get(linkage.agentId) ?? new Map()
|
||||
parents.delete(linkage.providerParentRef)
|
||||
parents.set(linkage.providerParentRef, linkage)
|
||||
reading.parents.set(linkage.agentId, parents)
|
||||
}
|
||||
if (body.kind === 'message') {
|
||||
for (const block of body.blocks.filter(isBackgroundTaskBlock)) {
|
||||
const index = reading.backgrounds.get(block.taskId) ?? { aliases: new Map() }
|
||||
indexClaudeBackgroundTask(index, itemId, block.taskId, block.parentToolUseId, linkage)
|
||||
reading.backgrounds.set(block.taskId, index)
|
||||
}
|
||||
}
|
||||
readAgentRow(reading, linkage)
|
||||
if (body.kind === 'message' && linkage.agentId === undefined) {
|
||||
for (const entry of body.blocks.flatMap(namedSubagents)) {
|
||||
|
||||
@@ -31,6 +31,7 @@ export type ClaudeSubagentLinkageDeps = {
|
||||
isForwardedParentTool?: (toolUseId: string) => boolean
|
||||
/** Map sidechain tool calls to their child owner to identify grandchildren's parents. */
|
||||
childOwnerRefOf?: (toolUseId: string) => string | null
|
||||
parentTaskOf?: (canonicalId: string) => string | undefined
|
||||
spawnRefOf?: (canonicalId: string) => string | null
|
||||
}
|
||||
|
||||
@@ -62,14 +63,16 @@ export class ClaudeSubagentLinkage
|
||||
linkageForAgent = (agentId: string): AgentJournalProducerLinkage => {
|
||||
const spawnRef = this.deps.spawnRefOf?.(agentId) ?? null
|
||||
if (spawnRef === null) {
|
||||
return { agentId, producerKind: 'agent' }
|
||||
const parentAgentId = this.deps.parentTaskOf?.(agentId)
|
||||
return { agentId, producerKind: 'agent', ...(parentAgentId ? { parentAgentId } : {}) }
|
||||
}
|
||||
const { linkage } = this.settledLinkageFor(spawnRef)
|
||||
const { parentAgentId, ...rest } = linkage
|
||||
const parent = this.deps.parentTaskOf?.(agentId) ?? parentAgentId
|
||||
return {
|
||||
...rest,
|
||||
agentId,
|
||||
...(parentAgentId === undefined || parentAgentId === agentId ? {} : { parentAgentId })
|
||||
...(parent === undefined || parent === agentId ? {} : { parentAgentId: parent })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +128,10 @@ export class ClaudeSubagentLinkage
|
||||
settled: boolean,
|
||||
depth: number
|
||||
): ParentAgentVerdict {
|
||||
const explicit = this.deps.parentTaskOf?.(this.deps.ids.canonical(parentToolUseId))
|
||||
if (explicit !== undefined) {
|
||||
return { kind: 'known', agentId: explicit }
|
||||
}
|
||||
const ownerRef = this.deps.childOwnerRefOf?.(parentToolUseId) ?? null
|
||||
if (ownerRef === null || depth >= MAX_PARENT_RESOLUTION_DEPTH) {
|
||||
return { kind: 'known' }
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { PARENT_TASK_STOP } from './claude-parent-task-frames.test-fixture'
|
||||
import { blockOf } from './claude-background-task-row-test-support'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -102,10 +104,13 @@ async function openJournal(): Promise<AgentSessionJournal> {
|
||||
})
|
||||
}
|
||||
|
||||
function acquire(journal: AgentSessionJournal) {
|
||||
function acquire(journal: AgentSessionJournal, delayed = false) {
|
||||
const deferred = createDeferredStructuredAgentSessionEventSink(testEventSinkLogging())
|
||||
const translator = createClaudeJournalTranslator({ sink: deferred.sink, coalesceMs: 0 })
|
||||
deferred.bind({ journal, fence: 1, publish: () => {} })
|
||||
const bind = () => deferred.bind({ journal, fence: 1, publish: () => {} })
|
||||
if (!delayed) {
|
||||
bind()
|
||||
}
|
||||
const settle = async (): Promise<void> => {
|
||||
await expect(deferred.drained()).resolves.toEqual({ ok: true })
|
||||
}
|
||||
@@ -115,7 +120,7 @@ function acquire(journal: AgentSessionJournal) {
|
||||
translator.dispose()
|
||||
deferred.close()
|
||||
}
|
||||
return { translator, settle, exit }
|
||||
return { translator, settle, exit, bind }
|
||||
}
|
||||
|
||||
const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRenderItem | undefined =>
|
||||
@@ -128,6 +133,85 @@ const proseRow = (journal: AgentSessionJournal, text: string): AgentJournalRende
|
||||
)
|
||||
|
||||
describe('a Claude subagent resumed after its provider restarted', () => {
|
||||
it.each(['terminal-only', 'roster-first', 'unbound-roster-first', 'parent-omitting-roster'])(
|
||||
'retains one owned shell across close/reopen: %s',
|
||||
async (order) => {
|
||||
let journal = await openJournal()
|
||||
const first = acquire(journal)
|
||||
first.translator.handle(userTurn('parent-task-turn'))
|
||||
// Contract: a parentless admission can learn ownership from a later roster without a body change.
|
||||
first.translator.handle(
|
||||
frame({ ...PARENT_TASK_STOP[3]!.frame, parent_task_id: undefined, tool_use_id: undefined })
|
||||
)
|
||||
await first.settle()
|
||||
const beforeOwnership = journal
|
||||
.snapshot()
|
||||
.items.find((item) => blockOf(item.body)?.taskId === 'shell-child')
|
||||
expect(beforeOwnership?.agentId).toBeUndefined()
|
||||
first.translator.handle(frame(PARENT_TASK_STOP[2]!.frame))
|
||||
await first.settle()
|
||||
expect(journal.item(beforeOwnership!.itemId)).toMatchObject({
|
||||
agentId: 'shell-child',
|
||||
parentAgentId: 'agent-parent'
|
||||
})
|
||||
first.translator.handle(frame(PARENT_TASK_STOP[3]!.frame))
|
||||
await first.settle()
|
||||
const shell = journal
|
||||
.snapshot()
|
||||
.items.find((item) => blockOf(item.body)?.taskId === 'shell-child')
|
||||
expect(shell).toMatchObject({
|
||||
agentId: 'shell-child',
|
||||
parentAgentId: 'agent-parent',
|
||||
producerKind: 'background',
|
||||
providerParentRef: 'toolu_shell'
|
||||
})
|
||||
await first.exit()
|
||||
expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('unverifiable')
|
||||
await journals.closeAll()
|
||||
|
||||
journal = await openJournal()
|
||||
const delayed = order === 'unbound-roster-first'
|
||||
const resumed = acquire(journal, delayed)
|
||||
if (!delayed) {
|
||||
expect(resumed.translator.childTaskParent?.('shell-child')).toBe('agent-parent')
|
||||
}
|
||||
if (order === 'parent-omitting-roster') {
|
||||
resumed.translator.handle(
|
||||
frame({
|
||||
type: 'system',
|
||||
subtype: 'background_tasks_changed',
|
||||
tasks: [{ task_id: 'shell-child', task_type: 'local_bash' }]
|
||||
})
|
||||
)
|
||||
await resumed.settle()
|
||||
expect(journal.item(shell!.itemId)).toMatchObject({ parentAgentId: 'agent-parent' })
|
||||
expect(blockOf(journal.item(shell!.itemId)?.body)?.state).toBe('working')
|
||||
} else if (order !== 'terminal-only') {
|
||||
resumed.translator.handle(frame(PARENT_TASK_STOP[2]!.frame))
|
||||
resumed.translator.handle(frame(PARENT_TASK_STOP[3]!.frame))
|
||||
}
|
||||
if (delayed) {
|
||||
resumed.bind()
|
||||
}
|
||||
// Contract: a terminal revision must retain saved ownership even without a repeated start.
|
||||
resumed.translator.handle(frame(PARENT_TASK_STOP[8]!.frame))
|
||||
await resumed.settle()
|
||||
const shells = journal
|
||||
.snapshot()
|
||||
.items.filter((item) => blockOf(item.body)?.taskId === 'shell-child')
|
||||
expect(shells).toHaveLength(1)
|
||||
expect(shells[0]).toMatchObject({
|
||||
itemId: shell!.itemId,
|
||||
agentId: 'shell-child',
|
||||
parentAgentId: 'agent-parent',
|
||||
producerKind: 'background',
|
||||
providerParentRef: 'toolu_shell'
|
||||
})
|
||||
expect(blockOf(shells[0]?.body)?.state).toBe('idle')
|
||||
await resumed.exit()
|
||||
}
|
||||
)
|
||||
|
||||
it('keeps the canonical id its first run was given, so one child stays one child', async () => {
|
||||
const journal = await openJournal()
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { AgentChildWorkKind } from '../../shared/agent-status/child-work/agent-status-child-work'
|
||||
// Task IDs alone cannot distinguish agents from shells or workflows; task_type identifies the kind.
|
||||
|
||||
import {
|
||||
@@ -63,3 +64,10 @@ export function readClaudeSubagentTaskFrame(
|
||||
excluded: announcement && !subagent
|
||||
}
|
||||
}
|
||||
|
||||
/** Releases predating `task_type` still name an agent in `subagent_type`. */
|
||||
export function claudeStartedTaskKind(message: Record<string, unknown>): AgentChildWorkKind {
|
||||
return isClaudeSubagentTask(message)
|
||||
? 'agent'
|
||||
: classifyClaudeBackgroundTaskKind(message.task_type)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { record, taskAliasId, taskId } from './claude-background-task-frames'
|
||||
import type { ClaudeBackgroundTaskDescriptor } from './claude-background-task-identity'
|
||||
|
||||
export type ClaudeTaskInvocation = {
|
||||
toolUseId?: string
|
||||
parentTaskId?: string
|
||||
/** Only current provider evidence may correct durable producer attribution. */
|
||||
reportedParentTaskId?: string
|
||||
excluded: boolean
|
||||
monitor: boolean
|
||||
ended?: { status: string; toolUseId?: string }
|
||||
/** Only accepted current evidence proves an alias is historical after replacement. */
|
||||
observed: boolean
|
||||
}
|
||||
|
||||
type Selection = { invocation: ClaudeTaskInvocation; current: boolean; acceptsStart: boolean }
|
||||
type Task = { current: ClaudeTaskInvocation; aliases: Map<string, ClaudeTaskInvocation> }
|
||||
|
||||
/** Acquisition-local provider facts; saved ownership never establishes a live task. */
|
||||
export class ClaudeTaskInvocations {
|
||||
private readonly tasks = new Map<string, Task>()
|
||||
private readonly observations = new WeakMap<object, Map<string, Selection>>()
|
||||
|
||||
constructor(
|
||||
private readonly saved?: {
|
||||
background: (id: string, run?: string) => ClaudeBackgroundTaskDescriptor | undefined
|
||||
parent: (id: string, run?: string) => string | undefined
|
||||
}
|
||||
) {}
|
||||
|
||||
observe(message: Record<string, unknown>): void {
|
||||
if (message.type !== 'system' || this.observations.has(message)) {
|
||||
return
|
||||
}
|
||||
const selections = new Map<string, Selection>()
|
||||
this.observations.set(message, selections)
|
||||
const roster = message.subtype === 'background_tasks_changed'
|
||||
const entries = roster && Array.isArray(message.tasks) ? message.tasks : [message]
|
||||
for (const entry of entries) {
|
||||
const frame = record(entry)
|
||||
const id = frame && taskId(frame)
|
||||
if (!frame || !id) {
|
||||
continue
|
||||
}
|
||||
const run = taskAliasId(frame.tool_use_id) ?? taskAliasId(record(frame.patch)?.tool_use_id)
|
||||
const start = message.subtype === 'task_started'
|
||||
const selection = this.select(id, run, start)
|
||||
const { invocation, acceptsStart } = selection
|
||||
if ((!start && !roster) || acceptsStart) {
|
||||
invocation.observed ||= selection.current
|
||||
invocation.toolUseId ??= run
|
||||
invocation.reportedParentTaskId =
|
||||
taskAliasId(frame.parent_task_id) ?? invocation.reportedParentTaskId
|
||||
invocation.parentTaskId = invocation.reportedParentTaskId ?? invocation.parentTaskId
|
||||
invocation.excluded ||= frame.ambient === true || frame.skip_transcript === true
|
||||
if (start && acceptsStart) {
|
||||
invocation.ended = undefined
|
||||
}
|
||||
}
|
||||
if (message.subtype === 'task_notification') {
|
||||
invocation.ended = { status: String(frame.status), toolUseId: invocation.toolUseId }
|
||||
}
|
||||
if (invocation.toolUseId) {
|
||||
this.tasks.get(id)!.aliases.set(invocation.toolUseId, invocation)
|
||||
}
|
||||
selections.set(id, selection)
|
||||
if (roster) {
|
||||
this.observations.set(frame, new Map([[id, selection]]))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
selection(message: Record<string, unknown>, id: string): Selection | undefined {
|
||||
this.observe(message)
|
||||
return this.observations.get(message)?.get(id)
|
||||
}
|
||||
|
||||
get(id: string, run?: string): ClaudeTaskInvocation | undefined {
|
||||
const task = this.tasks.get(id)
|
||||
return run === undefined
|
||||
? task?.current
|
||||
: (task?.aliases.get(run) ??
|
||||
(task?.current.toolUseId === undefined ? task?.current : undefined))
|
||||
}
|
||||
|
||||
parentOf = (id: string, run?: string): string | undefined => {
|
||||
const task = this.tasks.get(id)
|
||||
const invocation = run === undefined ? task?.current : task?.aliases.get(run)
|
||||
return invocation
|
||||
? invocation.parentTaskId
|
||||
: (this.saved?.background(id, run)?.linkage.parentAgentId ?? this.saved?.parent(id, run))
|
||||
}
|
||||
|
||||
excludeMonitor(id: string, run?: string): void {
|
||||
this.select(id, taskAliasId(run), true).invocation.monitor = true
|
||||
}
|
||||
|
||||
settle(id: string, status: unknown, run?: string): void {
|
||||
const invocation = this.get(id, run)
|
||||
if (invocation) {
|
||||
invocation.ended = { status: String(status), toolUseId: invocation.toolUseId }
|
||||
}
|
||||
}
|
||||
|
||||
settleFrame(id: string, message: Record<string, unknown>): void {
|
||||
this.settle(
|
||||
id,
|
||||
record(message.patch)?.status ?? message.status,
|
||||
taskAliasId(message.tool_use_id) ?? taskAliasId(record(message.patch)?.tool_use_id)
|
||||
)
|
||||
}
|
||||
|
||||
clear(): void {
|
||||
this.tasks.clear()
|
||||
}
|
||||
|
||||
private select(id: string, run: string | undefined, start: boolean): Selection {
|
||||
let task = this.tasks.get(id)
|
||||
if (!task) {
|
||||
const latest = this.saved?.background(id)
|
||||
const current = this.recover(id, latest ? undefined : run)
|
||||
task = { current, aliases: new Map() }
|
||||
if (current.toolUseId) {
|
||||
task.aliases.set(current.toolUseId, current)
|
||||
}
|
||||
this.tasks.set(id, task)
|
||||
}
|
||||
let invocation = task.current
|
||||
if (run !== undefined && invocation.toolUseId !== undefined && invocation.toolUseId !== run) {
|
||||
const saved = this.saved?.background(id, run)
|
||||
invocation = task.aliases.get(run) ?? this.recover(id, run)
|
||||
// A known historical alias cannot replace the current invocation; a pending tool result can.
|
||||
if (
|
||||
start &&
|
||||
!invocation.observed &&
|
||||
saved?.toolUseId !== run &&
|
||||
(task.current.ended !== undefined || !task.current.observed)
|
||||
) {
|
||||
task.current = invocation
|
||||
}
|
||||
task.aliases.set(run, invocation)
|
||||
}
|
||||
const current = task.current === invocation
|
||||
return {
|
||||
invocation,
|
||||
current,
|
||||
acceptsStart:
|
||||
current &&
|
||||
(invocation.ended === undefined ||
|
||||
(start &&
|
||||
(invocation.ended.status === 'completed' || invocation.ended.toolUseId === undefined)))
|
||||
}
|
||||
}
|
||||
|
||||
private recover(id: string, run?: string): ClaudeTaskInvocation {
|
||||
const descriptor = this.saved?.background(id, run)
|
||||
return {
|
||||
toolUseId: run ?? descriptor?.toolUseId,
|
||||
parentTaskId: descriptor?.linkage.parentAgentId ?? this.saved?.parent(id, run),
|
||||
observed: false,
|
||||
excluded: false,
|
||||
monitor: false
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { ClaudeProfileRouter } from '../../claude-accounts/claude-profile-router'
|
||||
import * as installedRouter from '../../claude-accounts/claude-profile-installed-router'
|
||||
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('reads only cached support and rejects a retired acquisition or changed account/context', async () => {
|
||||
const cliFlag = vi.fn(async () => 'supported' as const)
|
||||
const cli = fakeClaude()
|
||||
const router = new ClaudeProfileRouter({
|
||||
getSettings: () => ({
|
||||
claudeManagedAccounts: [],
|
||||
activeClaudeManagedAccountId: null,
|
||||
agentStatusHooksEnabled: false,
|
||||
disabledTuiAgents: []
|
||||
}),
|
||||
dataRoot: '/isolated',
|
||||
userHome: '/users/test',
|
||||
env: {}
|
||||
})
|
||||
const preparation = vi.spyOn(router, 'preparation')
|
||||
vi.spyOn(installedRouter, 'getClaudeProfileRouter').mockReturnValue(router)
|
||||
const adapter = await acquired(cli, {
|
||||
cliFlag,
|
||||
account: 'system',
|
||||
claudeConfigDir: '/accounts/claude',
|
||||
accountRecipe: { route: 'system', home: '/accounts/claude', configDir: '/accounts/claude' }
|
||||
})
|
||||
try {
|
||||
const record = agentSessionRecordFixture()
|
||||
record.sessionId = 'session-1'
|
||||
record.accountHome = { variable: 'CLAUDE_CONFIG_DIR', path: '/accounts/claude' }
|
||||
record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID
|
||||
const generate = vi.fn(async () => 'Broken chat title')
|
||||
cli.connections[0]!.generateSessionTitle = generate
|
||||
const owner = adapter.captureConversationTitleOwner(record)!
|
||||
expect(owner.isCurrent(record)).toBe(true)
|
||||
expect(await owner.generate('Repair login', () => owner.isCurrent(record))).toBe(
|
||||
'Broken chat title'
|
||||
)
|
||||
expect(cliFlag).toHaveBeenLastCalledWith(
|
||||
{ option: 'generate_session_title', firstVersion: '2.1.310' },
|
||||
250,
|
||||
false
|
||||
)
|
||||
expect(
|
||||
owner.isCurrent({ ...record, accountHome: { variable: 'CLAUDE_CONFIG_DIR', path: '/other' } })
|
||||
).toBe(false)
|
||||
expect(
|
||||
owner.isCurrent({
|
||||
...record,
|
||||
providerContextBoundary: { operationId: 'clear-1', afterFence: 7, clearedAt: 1 }
|
||||
})
|
||||
).toBe(false)
|
||||
const system = router.preparation()
|
||||
preparation.mockReturnValue({
|
||||
...system,
|
||||
provenance: 'profile:other',
|
||||
configDir: '/accounts/other'
|
||||
})
|
||||
expect(owner.isCurrent(record)).toBe(false)
|
||||
preparation.mockReturnValue(system)
|
||||
expect(owner.isCurrent(record)).toBe(true)
|
||||
await adapter.closeAll()
|
||||
expect(owner.isCurrent(record)).toBe(false)
|
||||
} finally {
|
||||
await adapter.closeAll()
|
||||
cli.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it.each(['unknown', 'unsupported'] as const)(
|
||||
'keeps %s CLIs on the existing generator path',
|
||||
async (support) => {
|
||||
const cli = fakeClaude()
|
||||
const adapter = await acquired(cli, { cliFlag: async () => support })
|
||||
try {
|
||||
const record = agentSessionRecordFixture()
|
||||
record.sessionId = 'session-1'
|
||||
record.providerHandleChain[0]!.handle.nativeId = PROVIDER_SESSION_ID
|
||||
const generate = vi.fn(async () => 'Do not use')
|
||||
cli.connections[0]!.generateSessionTitle = generate
|
||||
const owner = adapter.captureConversationTitleOwner(record)!
|
||||
expect(await owner.generate('Repair login', () => true)).toBeNull()
|
||||
expect(generate).not.toHaveBeenCalled()
|
||||
} finally {
|
||||
await adapter.closeAll()
|
||||
cli.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
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()
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import { resolve } from 'node:path'
|
||||
import { getClaudeProfileRouter } from '../../claude-accounts/claude-profile-installed-router'
|
||||
import { agentSessionAccountHomesEqual } from '../../../shared/agent-session/lifecycle/agent-session-account-home'
|
||||
import { claudeNamingContextId } from '../claude-conversation-naming'
|
||||
import { CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS } from '../claude-cli-flag-support'
|
||||
import type { StructuredAgentSessionAdapter } from '../../native-chat/agent-session-wire/providers/structured-agent-session-adapter'
|
||||
import type { ClaudeSession } from './claude-structured-session-state'
|
||||
|
||||
export const captureClaudeConversationTitleOwner =
|
||||
(
|
||||
sessions: Map<string, ClaudeSession>
|
||||
): NonNullable<StructuredAgentSessionAdapter['captureConversationTitleOwner']> =>
|
||||
(record) => {
|
||||
const session = sessions.get(record.sessionId)
|
||||
if (!session) {
|
||||
return null
|
||||
}
|
||||
const { connection, acquisitionGeneration, fence, providerSessionId, initialization } = session
|
||||
const boundary = record.providerContextBoundary?.operationId
|
||||
const account = () => {
|
||||
try {
|
||||
const policy = getClaudeProfileRouter()?.preparation()
|
||||
const recipe = initialization.accountRecipe
|
||||
if (policy) {
|
||||
if ((recipe?.route ?? initialization.account) === 'managed') {
|
||||
if (
|
||||
!policy.provenance.startsWith('profile:') ||
|
||||
(recipe?.route === 'managed' &&
|
||||
policy.provenance !== `profile:${recipe.accountId}`) ||
|
||||
resolve(initialization.cwd, policy.configDir) !== initialization.claudeConfigDir
|
||||
) {
|
||||
return null
|
||||
}
|
||||
} else if (policy.provenance !== 'system') {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return JSON.stringify([
|
||||
policy?.provenance,
|
||||
policy?.provenance.startsWith('profile:') ? policy.configDir : null
|
||||
])
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
const selectedAccount = account()
|
||||
const isCurrent: NonNullable<
|
||||
ReturnType<NonNullable<StructuredAgentSessionAdapter['captureConversationTitleOwner']>>
|
||||
>['isCurrent'] = (current) =>
|
||||
sessions.get(record.sessionId) === session &&
|
||||
session.connection === connection &&
|
||||
!connection.closed &&
|
||||
!session.closeFinalization &&
|
||||
session.acquisitionGeneration === acquisitionGeneration &&
|
||||
session.fence === fence &&
|
||||
current.lease.runtimeFence === fence &&
|
||||
current.provider === 'claude' &&
|
||||
session.providerSessionId === providerSessionId &&
|
||||
claudeNamingContextId(current) === providerSessionId &&
|
||||
current.providerContextBoundary?.operationId === boundary &&
|
||||
agentSessionAccountHomesEqual(current.accountHome, record.accountHome) &&
|
||||
current.location.workspaceId === record.location.workspaceId &&
|
||||
current.location.executionHostId === record.location.executionHostId &&
|
||||
session.initialization === initialization &&
|
||||
selectedAccount !== null &&
|
||||
account() === selectedAccount
|
||||
return {
|
||||
isCurrent,
|
||||
generate: async (firstPrompt, shouldExecute) => {
|
||||
if (
|
||||
!session.initialization.startup.opened() ||
|
||||
!connection.generateSessionTitle ||
|
||||
!shouldExecute()
|
||||
) {
|
||||
return null
|
||||
}
|
||||
// Verified support floor, not the request's introduction version; never start a probe here.
|
||||
const supported = await session.cliFlag?.(
|
||||
{ option: 'generate_session_title', firstVersion: '2.1.310' },
|
||||
CLAUDE_CACHED_FLAG_CHECK_BUDGET_MS,
|
||||
false
|
||||
)
|
||||
return supported === 'supported' && shouldExecute()
|
||||
? connection.generateSessionTitle?.(firstPrompt)
|
||||
: null
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { AgentSessionAcquisitionRootExitObservedError } from '../../native-chat/agent-session-wire/acquisition/structured-agent-session-acquisition-errors'
|
||||
|
||||
export function isKillDeliveredExitReceipt(
|
||||
receipt: Error | undefined
|
||||
): receipt is AgentSessionAcquisitionRootExitObservedError {
|
||||
return (
|
||||
receipt instanceof AgentSessionAcquisitionRootExitObservedError &&
|
||||
receipt.deathEvidenceKind === 'kill-delivered'
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user