Merge main and preserve localized voice settings

This commit is contained in:
Jinjing
2026-11-09 23:09:45 -08:00
249 changed files with 5551 additions and 6498 deletions
-1
View File
@@ -257,7 +257,6 @@
1 test-no-real-time-wait:src/main/windows/windows-process-tree-command-line-patch.test.ts
2 test-no-real-time-wait:src/main/windows/windows-pty-job.win32.test.ts
1 test-no-real-time-wait:src/main/worker-thread-child-process/worker-thread-child-process.test.ts
1 test-no-real-time-wait:src/main/workspaces/creation/preparation/worktree-create-preparation-cancellation.test.ts
1 test-no-real-time-wait:src/main/workspaces/removal/local-worktree-removal-recovery-live.test.ts
2 test-no-real-time-wait:src/main/wsl/execution/wsl-command-loop.test.ts
2 test-no-real-time-wait:src/main/wsl/orcad/wsl-orcad-real-distro-lane.test.ts
File diff suppressed because one or more lines are too long
@@ -1,87 +0,0 @@
import { describe, expect, it } from 'vitest'
import { CONSUMERS, consumerViolations, writerViolations } from './check-tab-map-seam-ratchet.mjs'
const BRIDGE =
'src/renderer/src/components/native-chat/session/status/StructuredAgentSessionStatusBridge.tsx'
const rules = CONSUMERS.get(BRIDGE)
describe('tab-map seam guard', () => {
it('rejects an ordinary handler reaching the cold path or walking a map', () => {
const text = [
'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)',
'const reconcile = () => reconcileFromSnapshot()',
'const ordinary = () => { reconcileFromSnapshot(); Object.keys(source) }'
].join('\n')
expect(consumerViolations('bridge.tsx', text, rules)).toEqual([
'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path',
'bridge.tsx:3 Object.keys outside a named cold path'
])
})
it('rejects an unreviewed value import, not type imports', () => {
const text = [
"import { wholeMap } from './new-walk'",
"import type { Walk } from './new-walk'"
].join('\n')
expect(consumerViolations('bridge.tsx', text, rules)).toEqual([
'bridge.tsx:1 imports wholeMap; repaired consumers import only reviewed helpers'
])
})
it('follows a raw record through a local binding unless it is marked full resync', () => {
const text = [
'function raw(state) {',
' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }',
' set({ unifiedTabsByWorktree: next })',
'}',
'function annotated(state) {',
' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }',
' markFullResync(next, "hydration")',
' set({ unifiedTabsByWorktree: next })',
'}'
].join('\n')
expect(writerViolations('writer.ts', text)).toEqual([
'writer.ts:3 raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync'
])
})
it('follows aliases of cold helpers and enumerators', () => {
const text = [
'const reconcileFromSnapshot = () => getStructuredAgentSessionTabs(source)',
'const reconcile = () => reconcileFromSnapshot()',
'const resync = reconcileFromSnapshot',
'const keys = Object.keys'
].join('\n')
expect(consumerViolations('bridge.tsx', text, rules)).toEqual([
'bridge.tsx:3 reconcileFromSnapshot() outside a named cold path',
'bridge.tsx:4 Object.keys outside a named cold path'
])
})
it('follows aliased raw records and requires annotation before publication', () => {
const raw =
'raw unifiedTabsByWorktree record; build it with a replace helper or draft, or mark it full resync'
const text = [
'function aliased(state) {',
' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }',
' const unifiedTabsByWorktree = next',
' set({ unifiedTabsByWorktree })',
'}',
'function late(state) {',
' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }',
' set({ unifiedTabsByWorktree: next })',
' markFullResync(next, "hydration")',
'}',
'function early(state) {',
' const next = { ...state.unifiedTabsByWorktree, [id]: tabs }',
' const alias = next',
' markFullResync(alias, "hydration")',
' set({ unifiedTabsByWorktree: alias })',
'}'
].join('\n')
expect(writerViolations('writer.ts', text)).toEqual([
`writer.ts:4 ${raw}`,
`writer.ts:8 ${raw}`
])
})
})
@@ -170,7 +170,8 @@ const NODE_RUNTIME_INCLUDE = [
'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts',
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts',
// Reopen the WAL-backed dismissal cache read-only through the row cache, which Bun on macOS cannot.
// Reopen WAL-backed row caches read-only, which Bun on macOS cannot.
'src/main/agent-hooks/server/testing/identity/server-hook-session-binding.test.ts',
'src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts',
'src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts',
'src/main/ipc/notifications-subject-retirement.test.ts',
@@ -4,7 +4,6 @@ import '../files/mobile-file-preview-operations'
import { aiVaultResumePreparationSchema } from './mobile-ai-vault-resume-reply-schema'
import '../browser/mobile-session-browser-reply-schema'
import '../files/session-documents/mobile-file-tap-reply-schema'
import '../transport/rpc/rpc-uninterpreted-reply-schemas'
// Legacy resume reads unsupported-method refusals raw to fall back to shared home.
export const aiVaultResumePreparationRun = bindDeferredRpcOperation(
@@ -4,7 +4,6 @@ import '../files/mobile-file-preview-operations'
import { browserTabCreatedSchema } from './mobile-session-browser-reply-schema'
import '../agent-history/mobile-ai-vault-resume-reply-schema'
import '../files/session-documents/mobile-file-tap-reply-schema'
import '../transport/rpc/rpc-uninterpreted-reply-schemas'
export const sessionBrowserTabCreate = bindDeferredRpcOperation(
defineRpcOperation({
@@ -44,31 +44,25 @@ afterEach(async () => {
})
describe('useNewWorkspaceRepositories initial repo', () => {
it.each([
{ order: 'desktop first', desktopFirst: true },
{ order: 'server first', desktopFirst: false }
])(
'picks the named host’s copy of a repo id two hosts share ($order)',
async ({ desktopFirst }) => {
const client = desktopListing(desktopFirst ? [repo()] : [])
let picked: MobileWorkspaceRepo | null = null
mounted = hookMount(() => {
picked = useNewWorkspaceRepositories({
client,
hostId: 'host-1',
visible: true,
initialRepo: { id: 'api', executionHostId: SERVER }
}).selectedRepo
})
mounted.mount()
await settleQueryNotifications()
// The desktop's same-id repo must not stand in while the server's listing is on its way.
expect(picked).toBeNull()
it('picks the named host’s copy of a repo id two hosts share', async () => {
const client = desktopListing([repo()])
let picked: MobileWorkspaceRepo | null = null
mounted = hookMount(() => {
picked = useNewWorkspaceRepositories({
client,
hostId: 'host-1',
visible: true,
initialRepo: { id: 'api', executionHostId: SERVER }
}).selectedRepo
})
mounted.mount()
await settleQueryNotifications()
// The desktop's same-id repo must not stand in while the server's listing is on its way.
expect(picked).toBeNull()
servers.repos = new Map([[SERVER, [repo(SERVER)]]])
act(() => mounted?.update())
await settleQueryNotifications()
expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER })
}
)
servers.repos = new Map([[SERVER, [repo(SERVER)]]])
act(() => mounted?.update())
await settleQueryNotifications()
expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER })
})
})
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/r
import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader'
import '../terminal/terminal-reply-schema'
import { workspaceFilePathsSchema } from './workspace-file-paths-reply-schema'
import '../session/agent-launch/mobile-agent-detection-reply-schema'
import './session-documents/mobile-markdown-tab-reply-schema'
import '../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../terminal/session/mobile-session-terminal-reply-schema'
import '../worktree/session-worktree-record-reply-schema'
import '../session/native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../terminal/quick-commands/mobile-quick-command-reply-schema'
// Skip refusals to retain suggestions; inspect method_not_found first to fall back from search to inventory.
export const nativeChatFileSearchRead = bindDeferredRpcOperation(
@@ -4,7 +4,6 @@ import '../mobile-file-preview-operations'
import { fileTapOpenedSchema } from './mobile-file-tap-reply-schema'
import '../../agent-history/mobile-ai-vault-resume-reply-schema'
import '../../browser/mobile-session-browser-reply-schema'
import '../../transport/rpc/rpc-uninterpreted-reply-schemas'
// Best-effort taps skip refused opens; explicit Changes-screen opens instead show the host error.
export const fileTapOpenRun = bindDeferredRpcOperation(
@@ -19,13 +19,6 @@ export const sessionMarkdownNoteCreate = bindDeferredRpcOperation(
import '../../terminal/terminal-reply-schema'
import { markdownTabDocumentSchema } from './mobile-markdown-tab-reply-schema'
import '../../session/agent-launch/mobile-agent-detection-reply-schema'
import '../../terminal/session/mobile-session-terminal-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../workspace-file-paths-reply-schema'
// Inspect renderer_unavailable before interpretation so headless hosts can fall back to disk.
export const markdownTabRead = bindDeferredRpcOperation(
@@ -38,8 +31,6 @@ export const markdownTabRead = bindDeferredRpcOperation(
})
)
import '../../session/tabs/mobile-session-tab-write-reply-schema'
import '../../terminal/quick-commands/mobile-quick-command-operations'
export const markdownTabSave = bindDeferredRpcOperation(
+15
View File
@@ -3364,6 +3364,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Zusammengeführt",
"closed": "Geschlossen",
"conflicts": "Konflikte",
"behind": "Nicht aktuell",
"blocked": "Blockiert",
"checksPending": "Prüfungen ausstehend",
"ableToMerge": "Zusammenführen möglich",
"unknown": "Unbekannt"
},
"pagination": {
"pageUnreachable": "Seite {{page}} liegt außerhalb des Bereichs der GitHub-Suche.",
"loadPageFailed": "Seite {{page}} konnte nicht von GitHub geladen werden.",
"noMoreResults": "Keine weiteren Ergebnisse auf Seite {{page}}."
},
"composerSource": {
"baseFailed": "Der Basis-Branch konnte nicht ermittelt werden.",
"forkPushWarning": "Bei diesem PR ist „Allow edits from maintainers“ deaktiviert; GitHub könnte einen Push zum Fork ablehnen."
+17 -2
View File
@@ -1502,11 +1502,11 @@
"updateRequired": "Actualiza Orca Mobile para abrir archivos PDF"
},
"unsavedEditsOffer": {
"changedSince": "Modificado en el escritorio desde tus cambios de las {{time}}",
"changedSince": "Modificado en el ordenador después de tus cambios de {{time}}",
"copyMyEdits": "Copiar mis cambios",
"discard": "Descartar",
"restore": "Restaurar",
"unsavedFrom": "Cambios sin guardar de las {{time}}"
"unsavedFrom": "Cambios sin guardar ({{time}})"
}
},
"home": {
@@ -3452,6 +3452,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Fusionado",
"closed": "Cerrado",
"conflicts": "Conflictos",
"behind": "Desactualizado",
"blocked": "Bloqueado",
"checksPending": "Comprobaciones pendientes",
"ableToMerge": "Se puede fusionar",
"unknown": "Desconocido"
},
"pagination": {
"pageUnreachable": "La página {{page}} está fuera del alcance de la búsqueda de GitHub.",
"loadPageFailed": "No se pudo cargar la página {{page}} desde GitHub.",
"noMoreResults": "No hay más resultados en la página {{page}}."
},
"composerSource": {
"baseFailed": "No se pudo resolver la rama base.",
"forkPushWarning": "Esta PR tiene desactivada la opción \"Allow edits from maintainers\"; GitHub podría rechazar el push al fork."
+15
View File
@@ -3452,6 +3452,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Fusionné",
"closed": "Fermé",
"conflicts": "Conflits",
"behind": "En retard",
"blocked": "Bloqué",
"checksPending": "Vérifications en attente",
"ableToMerge": "Fusion possible",
"unknown": "Inconnu"
},
"pagination": {
"pageUnreachable": "La page {{page}} dépasse la limite des résultats de recherche GitHub.",
"loadPageFailed": "La page {{page}} n’a pas pu être chargée depuis GitHub.",
"noMoreResults": "Aucun autre résultat sur la page {{page}}."
},
"composerSource": {
"baseFailed": "Échec de la résolution de la branche de base.",
"forkPushWarning": "L'option « Autoriser les modifications des mainteneurs » est désactivée pour cette PR ; le push vers le fork peut être refusé par GitHub."
+15
View File
@@ -3440,6 +3440,16 @@
"githubViewControls": {
"openView": "GitHub でビューを開く"
},
"hostedMerge": {
"merged": "マージ済み",
"closed": "クローズ済み",
"conflicts": "競合あり",
"behind": "遅れあり",
"blocked": "ブロック中",
"checksPending": "チェック待ち",
"ableToMerge": "マージ可能",
"unknown": "不明"
},
"itemActions": {
"changeStatus": "ステータスを変更",
"copyGitHubLink": "GitHub リンクをコピーする",
@@ -3586,6 +3596,11 @@
"updated": "更新日時",
"updatedSortDescription": "アクティビティが新しい順"
},
"pagination": {
"pageUnreachable": "ページ {{page}} は GitHub 検索で取得できる範囲を超えています。",
"loadPageFailed": "ページ {{page}} を GitHub から読み込めませんでした。",
"noMoreResults": "ページ {{page}} にこれ以上の結果はありません。"
},
"pickerProjection": {
"allRepos": "すべてのリポジトリ",
"allSites": "すべてのサイト",
+15
View File
@@ -3360,6 +3360,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "병합됨",
"closed": "닫힘",
"conflicts": "충돌",
"behind": "뒤처짐",
"blocked": "차단됨",
"checksPending": "검사 대기 중",
"ableToMerge": "병합 가능",
"unknown": "알 수 없음"
},
"pagination": {
"pageUnreachable": "{{page}}페이지는 GitHub 검색에서 반환할 수 있는 범위를 벗어났습니다.",
"loadPageFailed": "GitHub에서 {{page}}페이지를 불러오지 못했습니다.",
"noMoreResults": "{{page}}페이지에 더 이상 결과가 없습니다."
},
"composerSource": {
"baseFailed": "기본 브랜치를 확인하지 못했습니다.",
"forkPushWarning": "이 PR에서 \"유지 관리자의 수정 허용\"이 꺼져 있어 GitHub에서 포크로의 푸시를 거부할 수 있습니다."
+15
View File
@@ -3976,6 +3976,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Mesclado",
"closed": "Fechado",
"conflicts": "Conflitos",
"behind": "Desatualizado",
"blocked": "Bloqueado",
"checksPending": "Verificações pendentes",
"ableToMerge": "Pode ser mesclado",
"unknown": "Desconhecido"
},
"pagination": {
"pageUnreachable": "A página {{page}} está além do que a pesquisa do GitHub pode retornar.",
"loadPageFailed": "A página {{page}} não pôde ser carregada do GitHub.",
"noMoreResults": "Não há mais resultados na página {{page}}."
},
"composerSource": {
"baseFailed": "Falha ao determinar a branch base.",
"forkPushWarning": "Este PR está com \"Permitir edições de mantenedores\" desativado; o GitHub pode rejeitar o push para o fork."
+15
View File
@@ -3540,6 +3540,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Слито",
"closed": "Закрыто",
"conflicts": "Конфликты",
"behind": "Отстаёт",
"blocked": "Заблокировано",
"checksPending": "Проверки ожидаются",
"ableToMerge": "Можно слить",
"unknown": "Неизвестно"
},
"pagination": {
"pageUnreachable": "Страница {{page}} выходит за пределы результатов поиска GitHub.",
"loadPageFailed": "Не удалось загрузить страницу {{page}} из GitHub.",
"noMoreResults": "На странице {{page}} больше нет результатов."
},
"composerSource": {
"baseFailed": "Не удалось определить базовую ветку.",
"forkPushWarning": "В этом PR отключена настройка «Разрешить правки сопровождающим»; GitHub может отклонить отправку в форк."
+17 -2
View File
@@ -1461,11 +1461,11 @@
"updateRequired": "PDF'leri açmak için Orca Mobile'ı güncelleyin"
},
"unsavedEditsOffer": {
"changedSince": "{{time}} tarihli düzenlemelerinizden sonra masaüstünde değişti",
"changedSince": "Düzenlemelerinizden ({{time}}) sonra masaüstünde değişti",
"copyMyEdits": "Düzenlemelerimi kopyala",
"discard": "Vazgeç",
"restore": "Geri yükle",
"unsavedFrom": "{{time}} tarihli kaydedilmemiş düzenlemeler"
"unsavedFrom": "Kaydedilmemiş düzenlemeler ({{time}})"
}
},
"home": {
@@ -3364,6 +3364,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "Birleştirildi",
"closed": "Kapatıldı",
"conflicts": "Çakışmalar",
"behind": "Geride",
"blocked": "Engellendi",
"checksPending": "Kontroller bekleniyor",
"ableToMerge": "Birleştirilebilir",
"unknown": "Bilinmiyor"
},
"pagination": {
"pageUnreachable": "{{page}}. sayfa GitHub aramasının döndürebileceği aralığın dışında.",
"loadPageFailed": "{{page}}. sayfa GitHub’dan yüklenemedi.",
"noMoreResults": "{{page}}. sayfada başka sonuç yok."
},
"composerSource": {
"baseFailed": "Temel branch çözümlenemedi.",
"forkPushWarning": "Bu PR'da “Allow edits from maintainers” kapalı; fork'a push işlemi GitHub tarafından reddedilebilir."
+15
View File
@@ -3360,6 +3360,21 @@
}
},
"tasks": {
"hostedMerge": {
"merged": "已合併",
"closed": "已關閉",
"conflicts": "有衝突",
"behind": "落後",
"blocked": "已封鎖",
"checksPending": "等待檢查",
"ableToMerge": "可以合併",
"unknown": "未知"
},
"pagination": {
"pageUnreachable": "第 {{page}} 頁超出 GitHub 搜尋可傳回的範圍。",
"loadPageFailed": "無法從 GitHub 載入第 {{page}} 頁。",
"noMoreResults": "第 {{page}} 頁沒有更多結果。"
},
"composerSource": {
"baseFailed": "無法解析基礎分支。",
"forkPushWarning": "此 PR 未啟用「允許維護者編輯」;推送至分叉存放庫可能會遭 GitHub 拒絕。"
+15
View File
@@ -3449,6 +3449,16 @@
"githubViewControls": {
"openView": "在 GitHub 中打开视图"
},
"hostedMerge": {
"merged": "已合并",
"closed": "已关闭",
"conflicts": "有冲突",
"behind": "落后",
"blocked": "已阻止",
"checksPending": "检查待完成",
"ableToMerge": "可以合并",
"unknown": "未知"
},
"itemActions": {
"changeStatus": "更改状态",
"copyGitHubLink": "复制 GitHub 链接",
@@ -3595,6 +3605,11 @@
"updated": "已更新",
"updatedSortDescription": "最新活动优先"
},
"pagination": {
"pageUnreachable": "第 {{page}} 页超出了 GitHub 搜索可返回的范围。",
"loadPageFailed": "无法从 GitHub 加载第 {{page}} 页。",
"noMoreResults": "第 {{page}} 页没有更多结果。"
},
"pickerProjection": {
"allRepos": "所有仓库",
"allSites": "所有站点",
@@ -1,101 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { z } from 'zod'
import {
missedNotificationsSchema,
notificationUnreadReplySchema,
PUSH_REGISTER_REFUSAL_REASONS,
PUSH_TEST_REFUSAL_REASONS,
pushDeliveryTestResultSchema,
pushRouteRegistrationSchema
} from './notification-reply-schema'
function reads<T>(schema: z.ZodType<T, unknown>, value: unknown): T {
const parsed = schema.safeParse(value)
if (!parsed.success) {
throw new Error(`expected a readable reply: ${parsed.error.message}`)
}
return parsed.data
}
function refuses(schema: z.ZodType<unknown, unknown>, value: unknown): boolean {
return !schema.safeParse(value).success
}
describe('notification replies tolerate the shapes their call sites guard', () => {
it('reads a test-push reply the screen reaches through optional chaining', () => {
expect(reads(pushDeliveryTestResultSchema, { accepted: true })?.accepted).toBe(true)
expect(reads(pushDeliveryTestResultSchema, null)).toBe(null)
expect(reads(pushDeliveryTestResultSchema, undefined)).toBe(undefined)
expect(reads(pushDeliveryTestResultSchema, { error: 'refused' })?.accepted).toBe(undefined)
})
// Schema refusal would replace the screen’s generic send-failure copy with a parser error.
it('reads a non-object test-push result as absent, which takes the generic copy', () => {
for (const value of ['garbage', 7, true, []]) {
expect(refuses(pushDeliveryTestResultSchema, value)).toBe(false)
const result = reads(pushDeliveryTestResultSchema, value)
expect(result?.accepted).toBe(undefined)
expect(result?.reason).toBe(undefined)
}
})
it('reads a registration reply the reconciler reaches through optional chaining', () => {
expect(reads(pushRouteRegistrationSchema, { registered: true })?.registered).toBe(true)
expect(reads(pushRouteRegistrationSchema, null)).toBe(null)
expect(reads(pushRouteRegistrationSchema, { registered: 'yes' })?.registered).toBe(undefined)
})
it('takes every reply at the two sites whose body nothing reads', () => {
expect(refuses(notificationUnreadReplySchema, undefined)).toBe(false)
expect(refuses(notificationUnreadReplySchema, null)).toBe(false)
expect(refuses(notificationUnreadReplySchema, 'anything')).toBe(false)
})
})
describe('closed enums degrade to the copy main showed', () => {
it('keeps a reason the screen branches on and drops one it does not know', () => {
expect(
reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'rate_limited' })?.reason
).toBe('rate_limited')
expect(
reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'not_registered' })?.reason
).toBe('not_registered')
expect(reads(pushDeliveryTestResultSchema, { accepted: false, reason: 'quota' })?.reason).toBe(
undefined
)
})
it('keeps a registration reason and drops an unknown one', () => {
const reply = { registered: false, reason: 'throttled' }
expect(reads(pushRouteRegistrationSchema, reply)?.reason).toBe('throttled')
expect(
reads(pushRouteRegistrationSchema, { registered: false, reason: 'moon-phase' })?.reason
).toBe(undefined)
})
// Host-pinned unions cover every arm; these loops prove each survives parsing.
it('keeps every refusal reason the host declares for either route', () => {
for (const reason of PUSH_TEST_REFUSAL_REASONS) {
expect(reads(pushDeliveryTestResultSchema, { accepted: false, reason })?.reason).toBe(reason)
}
for (const reason of PUSH_REGISTER_REFUSAL_REASONS) {
expect(reads(pushRouteRegistrationSchema, { registered: false, reason })?.reason).toBe(reason)
}
})
})
describe('dismissal rows stay opaque', () => {
it('keeps every row for readPushNotificationIdentity to judge', () => {
const rows = [{ notificationId: 'n-1' }, 'not-a-row', 7]
expect(reads(missedNotificationsSchema, { dismissedPushes: rows })?.dismissedPushes).toEqual(
rows
)
})
it('drops a dismissedPushes that is not an array, as Array.isArray did', () => {
expect(reads(missedNotificationsSchema, { dismissedPushes: 'all' })?.dismissedPushes).toBe(
undefined
)
expect(reads(missedNotificationsSchema, null)).toBe(null)
})
})
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import '../../terminal/terminal-reply-schema'
import { detectedAgentsSchema, refreshedAgentsSchema } from './mobile-agent-detection-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../terminal/session/mobile-session-terminal-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../../files/workspace-file-paths-reply-schema'
// Launch detection surfaces host refusals; advisory task-drawer readers intentionally skip them.
export const preflightDetectAgentsRead = bindDeferredRpcOperation(
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import '../../terminal/terminal-reply-schema'
import { runtimeRepoListSchema } from './mobile-agent-detection-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../terminal/session/mobile-session-terminal-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../../files/workspace-file-paths-reply-schema'
export type MobileRuntimeRepoSummary = {
id: string
+1 -11
View File
@@ -1,9 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
FLOATING_WORKSPACE_WORKTREE_ID,
floatingWorkspaceSessionPath,
isFloatingWorkspaceWorktreeId
} from './floating-workspace'
import { isFloatingWorkspaceWorktreeId } from './floating-workspace'
describe('floating workspace routing', () => {
it('matches only the desktop sentinel id', () => {
@@ -13,10 +9,4 @@ describe('floating workspace routing', () => {
expect(isFloatingWorkspaceWorktreeId(undefined)).toBe(false)
expect(isFloatingWorkspaceWorktreeId(null)).toBe(false)
})
it('builds the session route with an explicit title seed', () => {
expect(floatingWorkspaceSessionPath('host-1')).toBe(
`/h/host-1/session/${FLOATING_WORKSPACE_WORKTREE_ID}?name=Floating%20Workspace`
)
})
})
@@ -1,77 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MobileSessionRouteScreen } from './MobileSessionRouteScreen'
// Mocked react-native components are string tags that ReactTestInstance's ElementType omits.
function hostType(node: ReactTestInstance): unknown {
return node.type
}
const state = vi.hoisted(() => ({
terminalPreferencesReady: false,
accessoryPreferencesReady: false,
nativeChatController: { sessionViewReady: false }
}))
const mounts = vi.hoisted(() => ({ count: 0 }))
vi.mock('react-native', () => ({
ActivityIndicator: 'ActivityIndicator',
Text: 'Text',
View: 'View'
}))
vi.mock('./mobile-session-styles', () => ({ styles: {} }))
vi.mock('./use-mobile-session-controller', () => ({ useMobileSessionController: () => state }))
vi.mock('./MobileSessionSurface', async () => {
const react = await import('react')
return {
MobileSessionSurface: () => {
react.useEffect(() => {
mounts.count += 1
}, [])
return react.createElement('ReadySession')
}
}
})
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
describe('first visible session appearance', () => {
it.each(['terminal', 'accessory', 'chat'] as const)(
'waits for the saved %s setting before mounting the session',
(waiting) => {
state.terminalPreferencesReady = waiting !== 'terminal'
state.accessoryPreferencesReady = waiting !== 'accessory'
state.nativeChatController.sessionViewReady = waiting !== 'chat'
mounts.count = 0
const render = () =>
act(() => {
if (renderer) {
renderer.update(createElement(MobileSessionRouteScreen))
} else {
renderer = create(createElement(MobileSessionRouteScreen))
}
})
const expectPreparing = () => {
expect(renderer?.root.findAll((node) => hostType(node) === 'ReadySession')).toHaveLength(0)
expect(
renderer?.root.findAll((node) => hostType(node) === 'ActivityIndicator')
).toHaveLength(1)
expect(mounts.count).toBe(0)
}
render()
expectPreparing()
state.terminalPreferencesReady = true
state.accessoryPreferencesReady = true
state.nativeChatController.sessionViewReady = true
render()
expect(renderer?.root.findAll((node) => hostType(node) === 'ReadySession')).toHaveLength(1)
expect(mounts.count).toBe(1)
render()
expect(mounts.count).toBe(1)
}
)
})
@@ -1,3 +0,0 @@
export type RuntimeStatusResult = {
capabilities?: string[]
}
@@ -1,213 +0,0 @@
import './MobileNativeChatView.harness.test-fixture'
import { createElement, type ReactNode } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
import { MobileNativeChatView } from './MobileNativeChatView'
const scrollToEnd = vi.hoisted(() => vi.fn())
const scrollToOffset = vi.hoisted(() => vi.fn())
vi.mock('react-native', async () => {
const React = await import('react')
return {
...(await import('../../test-support/react-native-motion-stub')).reactNativeMotionStub(),
ActivityIndicator: 'ActivityIndicator',
FlatList: React.forwardRef<
unknown,
{
data: NativeChatMessage[]
renderItem: (row: { item: NativeChatMessage; index: number }) => ReactNode
ListFooterComponent: ReactNode
}
>((props, ref) => {
React.useImperativeHandle(ref, () => ({ scrollToEnd, scrollToOffset }), [])
return React.createElement(
'FlatList',
props,
props.data.map((item, index) =>
React.createElement(React.Fragment, { key: item.id }, props.renderItem({ item, index }))
),
props.ListFooterComponent
)
}),
Platform: { OS: 'ios' },
Pressable: 'Pressable',
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 },
Text: 'Text',
View: 'View'
}
})
vi.mock('react-native-safe-area-context', () => ({
useSafeAreaInsets: () => ({ top: 0, bottom: 0, left: 0, right: 0 })
}))
vi.mock('react-native-gesture-handler', () => {
const chain = {
runOnJS: () => chain,
onStart: () => chain,
onUpdate: () => chain
}
return {
Gesture: { Simultaneous: () => ({}), Native: () => ({}), Pinch: () => chain },
GestureDetector: 'GestureDetector',
GestureHandlerRootView: 'GestureHandlerRootView'
}
})
vi.mock('lucide-react-native', () => ({
ArrowDown: 'ArrowDown',
ChevronsDownUp: 'ChevronsDownUp',
ChevronsUpDown: 'ChevronsUpDown',
Square: 'Square'
}))
vi.mock('./transcript/MobileNativeChatMessage', () => ({
MobileNativeChatMessage: 'ChatMessage'
}))
vi.mock('./transcript/MobileNativeChatLiveLine', () => ({
MobileNativeChatLiveLine: 'LiveStatus'
}))
vi.mock('./input/MobileNativeChatAsk', () => ({ MobileNativeChatAsk: 'ChatAsk' }))
vi.mock('./input/MobileNativeChatPermission', () => ({
MobileNativeChatPermission: 'ChatPermission'
}))
vi.mock('./input/MobileNativeChatQuestion', () => ({
MobileNativeChatQuestion: 'ChatQuestion'
}))
vi.mock('../../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
vi.mock('./composer/MobileNativeChatComposer', async () => {
const { composerStub } = await import('./MobileNativeChatView.render-stubs.test-fixture')
return composerStub()
})
type Overrides = {
messages?: Parameters<typeof MobileNativeChatView>[0]['messages']
folded?: Parameters<typeof MobileNativeChatView>[0]['folded']
streaming?: string | null
sendErrorMessage?: string | null
onClearSendError?: () => void
inputLockReason?: 'disconnected' | 'waiting' | null
onSend?: (text: string) => Promise<boolean>
pending?: Parameters<typeof MobileNativeChatView>[0]['pending']
structuredActivityUi?: boolean
turnIndicator?: Parameters<typeof MobileNativeChatView>[0]['turnIndicator']
agentWorking?: boolean
canStop?: boolean
ask?: Parameters<typeof MobileNativeChatView>[0]['ask']
question?: Parameters<typeof MobileNativeChatView>[0]['question']
permission?: Parameters<typeof MobileNativeChatView>[0]['permission']
sendSurfaceId?: string
keyboardInset?: number
hasMore?: boolean
onLoadEarlier?: () => void
}
function chatViewElement(overrides: Overrides): ReturnType<typeof createElement> {
return createElement(MobileNativeChatView, {
messages: [],
folded: [],
status: 'ready',
streaming: null,
onSend: vi.fn().mockResolvedValue(true),
sendSurfaceId: 'tab-a',
getSendCompletionGeneration: () => 0,
getComposerEditGeneration: () => 0,
pending: [],
draftKey: null,
onComposerTextChange: vi.fn(),
...overrides
})
}
describe('MobileNativeChatView', () => {
let renderer: ReactTestRenderer | null = null
beforeEach(() => {
vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>
setTimeout(() => callback(0), 0)
)
vi.stubGlobal('cancelAnimationFrame', (handle: ReturnType<typeof setTimeout>) =>
clearTimeout(handle)
)
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
scrollToEnd.mockReset()
scrollToOffset.mockReset()
vi.unstubAllGlobals()
})
async function render(overrides: Overrides = {}): Promise<void> {
await act(async () => {
renderer = create(chatViewElement(overrides))
})
}
async function update(overrides: Overrides = {}): Promise<void> {
await act(async () => {
renderer?.update(chatViewElement(overrides))
})
}
function renderedRow(id: string): ReturnType<typeof createElement> {
return createElement(
'Row',
renderer!.root.find(
(node) => String(node.type) === 'ChatMessage' && node.props.message.id === id
).props
)
}
describe('structured turn status wiring', () => {
const userTurn = (id: string, text: string): NativeChatMessage => ({
id,
role: 'user',
blocks: [{ type: 'text', text }],
timestamp: 0,
source: 'transcript'
})
function rowProps(id: string): Record<string, unknown> {
return (renderedRow(id) as { props: Record<string, unknown> }).props
}
it('does not carry a running turn clock across chat surfaces', async () => {
vi.useFakeTimers()
try {
vi.setSystemTime(1_000)
const firstTab = [userTurn('u1', 'first')]
await render({
messages: firstTab,
folded: firstTab,
structuredActivityUi: true,
agentWorking: true,
sendSurfaceId: 'host\0worktree\0tab-a'
})
expect(rowProps('u1').turnStatus).toMatchObject({ startedAt: 1_000 })
vi.setSystemTime(12_000)
const secondTab = [userTurn('u2', 'second')]
await update({
messages: secondTab,
folded: secondTab,
structuredActivityUi: true,
agentWorking: true,
sendSurfaceId: 'host\0worktree\0tab-b'
})
expect(rowProps('u2').turnStatus).toMatchObject({ startedAt: 12_000 })
} finally {
vi.useRealTimers()
}
})
})
})
vi.mock('./input/MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport
import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader'
import '../../../terminal/terminal-reply-schema'
import { sessionForwardedReplySchema } from '../../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../agent-launch/mobile-agent-detection-reply-schema'
import '../../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../../terminal/session/mobile-session-terminal-reply-schema'
import '../../../worktree/session-worktree-record-reply-schema'
import '../composer/mobile-native-chat-skill-reply-schema'
import '../../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../../../files/workspace-file-paths-reply-schema'
// Retain the live window on refusal and let the caller offer retry; read the whole legacy error/window union before selecting messages.
export const nativeChatSessionPageRead = bindDeferredRpcOperation(
@@ -1,166 +0,0 @@
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments'
import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
import {
useMobileNativeChatDraft,
setMobileNativeChatDraftText,
resetMobileNativeChatDraftStoreForTests
} from './mobile-native-chat-draft-store'
import {
subscribeMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs,
closeMobileNativeChatEditInputs,
useMobileNativeChatDraftInputs
} from './mobile-native-chat-draft-inputs'
const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker }))
afterEach(resetMobileNativeChatDraftStoreForTests)
it.each([20, 200])(
'isolates mounted text, input, image and file consumers across %i other scopes',
async (count) => {
const scopes = [
'own-host:target',
...Array.from({ length: count }, (_, i) => `other-host:${i}`)
]
const own = scopes[0]
const renders = scopes.map(() => ({ text: 0, input: 0, image: 0, file: 0 }))
const values: {
text: string
pending: number
images: readonly string[]
files: readonly string[]
}[] = scopes.map(() => ({ text: '', pending: 0, images: [], files: [] }))
const upstream = scopes.map(() => vi.fn())
const releases = scopes.map((scope, i) =>
subscribeMobileNativeChatDraftInputs(scope, upstream[i])
)
function Text({ index }: { index: number }) {
values[index].text = useMobileNativeChatDraft(scopes[index])
renders[index].text++
return null
}
function Input({ index }: { index: number }) {
values[index].pending = useMobileNativeChatDraftInputs(scopes[index]).pending ?? 0
renders[index].input++
return null
}
function File({ index }: { index: number }) {
const file = useMobileNativeChatFileAttachments({
client: null,
sessionId: null,
scopeKey: scopes[index],
enabled: false,
showToast: vi.fn()
})
values[index].files = file.files.map((entry) => entry.path ?? '')
renders[index].file++
return null
}
function Image({ index }: { index: number }) {
const image = useMobileNativeChatImageAttachments({
client: null,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'disconnected',
scopeKey: scopes[index],
enabled: false,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend: async () => 'rejected',
readSeededLaunchDraft: () => null
})
values[index].images = image.attachments.map((entry) => entry.path)
renders[index].image++
return null
}
let view: ReturnType<typeof create> | undefined
await act(async () => {
view = create(
createElement(
'fixture',
{},
scopes.flatMap((_, index) => [
createElement(Text, { key: `t${index}`, index }),
createElement(Input, { key: `p${index}`, index }),
createElement(File, { key: `f${index}`, index }),
createElement(Image, { key: `i${index}`, index })
])
)
)
})
renders.forEach((entry) => {
entry.text = entry.input = entry.image = entry.file = 0
})
try {
await act(async () => setMobileNativeChatDraftText(own, 'own text'))
expect(values[0].text).toBe('own text')
expect(renders[0]).toEqual({ text: 1, input: 0, image: 0, file: 0 })
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 1 }))
)
expect(values[0].pending).toBe(1)
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({
...current,
images: [{ id: 'image', path: '/saved.png', previewUri: 'file:///saved.png' }]
}))
)
expect(values[0].images).toEqual(['/saved.png'])
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({
...current,
files: [
{ id: 'file', path: '/saved.txt', name: 'saved.txt', mime: 'text/plain', byteLength: 1 }
]
}))
)
expect(values[0].files).toEqual(['/saved.txt'])
expect(renders[0]).toEqual({ text: 1, input: 3, image: 2, file: 1 })
expect(upstream[0]).toHaveBeenCalledTimes(3)
for (let index = 1; index < scopes.length; index++) {
expect(renders[index]).toEqual({ text: 0, input: 0, image: 0, file: 0 })
expect(upstream[index]).not.toHaveBeenCalled()
}
} finally {
await act(async () => view?.unmount())
releases.forEach((release) => release())
}
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 0 }))
)
expect(renders[0]).toEqual({ text: 1, input: 3, image: 2, file: 1 })
expect(upstream[0]).toHaveBeenCalledTimes(3)
}
)
it.each([20, 200])(
'notifies only affected scopes across %i retained input subscribers and retires listeners',
(count) => {
const idle = vi.fn()
const releases = Array.from({ length: count }, (_, index) =>
subscribeMobileNativeChatDraftInputs(`idle-${index}`, idle)
)
const source = vi.fn()
const destination = vi.fn()
releases.push(
subscribeMobileNativeChatDraftInputs('queued-edit:one', source),
subscribeMobileNativeChatDraftInputs('bottom', destination)
)
updateMobileNativeChatDraftInputs('queued-edit:one', (inputs) => ({ ...inputs, pending: 1 }))
expect(source).toHaveBeenCalledTimes(1)
expect(idle).not.toHaveBeenCalled()
closeMobileNativeChatEditInputs('queued-edit:one', 'bottom')
expect(source).toHaveBeenCalledTimes(2)
expect(destination).toHaveBeenCalledTimes(1)
expect(idle).not.toHaveBeenCalled()
releases.forEach((release) => release())
updateMobileNativeChatDraftInputs('bottom', (inputs) => ({ ...inputs, pending: 0 }))
expect(destination).toHaveBeenCalledTimes(1)
}
)
@@ -1,8 +1,5 @@
import { describe, expect, it } from 'vitest'
import {
MobileFileTooLargeError,
type PickedMobileFile
} from '../../../platform/media-picker-contract'
import type { PickedMobileFile } from '../../../platform/media-picker-contract'
import {
nativeChatTextWithFileReferences,
uploadPickedNativeChatFiles,
@@ -83,20 +80,4 @@ describe('uploadPickedNativeChatFiles', () => {
expect([...chips.values()].map((chip) => chip.path)).toEqual(['/store/a.txt', '/store/b.txt'])
expect(errors).toEqual([])
})
it('drops the chip of a failed upload, says which file, and carries on', async () => {
const { chips, errors, done } = run(pickedFiles([picked('a.txt'), picked('b.txt')]), 'a.txt')
await done
expect([...chips.values()].map((chip) => chip.name)).toEqual(['b.txt'])
expect(errors).toEqual(["Couldn't upload a.txt"])
})
it('keeps what was stored before the picker refused an oversized file', async () => {
const { chips, errors, done } = run(
pickedFiles([picked('a.txt')], new MobileFileTooLargeError('clip.mov'))
)
await done
expect([...chips.values()].map((chip) => chip.name)).toEqual(['a.txt'])
expect(errors).toEqual([new MobileFileTooLargeError('clip.mov').message])
})
})
@@ -1,18 +0,0 @@
import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment'
export const NO_NATIVE_CHAT_IMAGE_ATTACHMENTS: PendingNativeChatImage[] = []
export type MobileNativeChatImagesByScope = Record<string, PendingNativeChatImage[]>
export function withScopeAttachments<List extends readonly unknown[]>(
byScope: Readonly<Record<string, List>>,
scope: string,
next: List
): Record<string, List> {
if (next.length > 0) {
return { ...byScope, [scope]: next }
}
const remaining = { ...byScope }
delete remaining[scope]
return remaining
}
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../../transport
import { rpcResultVariant } from '../../../transport/rpc/rpc-operation-result-reader'
import '../../../terminal/terminal-reply-schema'
import { skillDiscoveryReplySchema } from './mobile-native-chat-skill-reply-schema'
import '../../agent-launch/mobile-agent-detection-reply-schema'
import '../../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../../terminal/session/mobile-session-terminal-reply-schema'
import '../../../worktree/session-worktree-record-reply-schema'
import '../../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../../../files/workspace-file-paths-reply-schema'
// Mobile names the workspace and lets the host resolve and scan it; see SKILL_DISCOVER_WORKSPACE_CAPABILITY.
export const nativeChatSkillDiscoveryRead = bindDeferredRpcOperation(
@@ -354,52 +354,6 @@ describe('useMobileNativeChatDrafts', () => {
expect(state?.composerText).toBe(' /clear')
})
it('reconciles an image-only unconfirmed send against the next user turn (no false warning)', async () => {
vi.useFakeTimers()
try {
await mount('a')
await act(async () =>
renderer?.update(
createElement(Harness, { tabId: 'a', messages: [assistantTextMessage('a1', 'hi')] })
)
)
const origin = state?.captureSendOrigin('')
const onUnconfirmed = vi.fn()
act(() => {
if (origin) {
state?.holdUnconfirmedSend(origin, '', onUnconfirmed)
}
})
await act(async () =>
renderer?.update(
createElement(Harness, {
tabId: 'a',
messages: [assistantTextMessage('a1', 'hi'), assistantTextMessage('a2', 'ok')]
})
)
)
await act(async () =>
renderer?.update(
createElement(Harness, {
tabId: 'a',
messages: [
assistantTextMessage('a1', 'hi'),
assistantTextMessage('a2', 'ok'),
userTextMessage('u1', '')
]
})
)
)
act(() => {
vi.advanceTimersByTime(30_000)
})
expect(onUnconfirmed).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('clears image-only echoes one per landed user turn, not all at once', async () => {
await mount('a')
await act(async () =>
@@ -430,59 +384,6 @@ describe('useMobileNativeChatDrafts', () => {
expect(state?.pending.map((pending) => pending.images)).toEqual([['file:///b.jpg']])
})
it('registers no deadline when the transcript echo beat the ambiguous RPC rejection', async () => {
vi.useFakeTimers()
try {
await mount('a')
const origin = state?.captureSendOrigin('ping')
const onUnconfirmed = vi.fn()
await act(async () =>
renderer?.update(
createElement(Harness, { tabId: 'a', messages: [userTextMessage('m1', 'ping')] })
)
)
act(() => {
if (origin) {
state?.holdUnconfirmedSend(origin, 'ping', onUnconfirmed)
}
})
expect(vi.getTimerCount()).toBe(0)
act(() => {
vi.advanceTimersByTime(30_000)
})
expect(onUnconfirmed).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('surfaces uncertainty when no echo lands before the deadline', async () => {
vi.useFakeTimers()
try {
await mount('a')
const origin = state?.captureSendOrigin('ping')
const onUnconfirmed = vi.fn()
act(() => {
if (origin) {
state?.holdUnconfirmedSend(origin, 'ping', onUnconfirmed)
}
})
act(() => {
vi.advanceTimersByTime(19_999)
})
expect(onUnconfirmed).not.toHaveBeenCalled()
act(() => {
vi.advanceTimersByTime(1)
})
expect(onUnconfirmed).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
it('does not confirm an unconfirmed send against an older identical turn', async () => {
vi.useFakeTimers()
try {
@@ -556,63 +457,6 @@ describe('useMobileNativeChatDrafts', () => {
}
})
it('requires one new transcript echo per repeated unconfirmed send', async () => {
vi.useFakeTimers()
try {
await mount('a')
act(() => state?.setComposerText('ping'))
const origin = state?.captureSendOrigin('ping')
const firstUnconfirmed = vi.fn()
const secondUnconfirmed = vi.fn()
act(() => {
if (origin) {
state?.holdUnconfirmedSend(origin, 'ping', firstUnconfirmed)
state?.holdUnconfirmedSend(origin, 'ping', secondUnconfirmed)
}
})
await act(async () =>
renderer?.update(
createElement(Harness, { tabId: 'a', messages: [userTextMessage('echo-1', 'ping')] })
)
)
act(() => {
vi.advanceTimersByTime(30_000)
})
expect(firstUnconfirmed).not.toHaveBeenCalled()
expect(secondUnconfirmed).toHaveBeenCalledTimes(1)
} finally {
vi.useRealTimers()
}
})
it('does not retain a deadline when an ambiguous send settles after unmount', async () => {
vi.useFakeTimers()
try {
await mount('a')
const origin = state?.captureSendOrigin('ping')
const holdUnconfirmedSend = state?.holdUnconfirmedSend
const onUnconfirmed = vi.fn()
act(() => renderer?.unmount())
renderer = null
act(() => {
if (origin) {
holdUnconfirmedSend?.(origin, 'ping', onUnconfirmed)
}
})
expect(vi.getTimerCount()).toBe(0)
act(() => {
vi.advanceTimersByTime(30_000)
})
expect(onUnconfirmed).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})
it('does not erase newer edits when an unconfirmed send lands', async () => {
await mount('a')
act(() => state?.setComposerText('submitted'))
@@ -52,7 +52,6 @@ type Props = Parameters<typeof MobileNativeChatBackgroundTasks>[0]
type StopResult = Awaited<ReturnType<Props['tasks']['stop']>>
const REJECTED: StopResult = { status: 'rejected' }
const UNCONFIRMED: StopResult = { status: 'unknown' }
const STOPPED: StopResult = { status: 'accepted', value: { cancelled: true }, sameFence: true }
const NOTHING_STOPPED: StopResult = {
status: 'accepted',
@@ -98,20 +97,6 @@ describe('MobileNativeChatBackgroundTasks', () => {
return mounted
}
function styleOf(node: ReactTestInstance): Record<string, unknown> {
const rendered: unknown =
typeof node.props.style === 'function'
? node.props.style({ pressed: false })
: node.props.style
const parts = Array.isArray(rendered) ? rendered : [rendered]
return Object.assign(
{},
...parts.filter(
(part): part is Record<string, unknown> => typeof part === 'object' && part !== null
)
)
}
function header(mounted: ReactTestRenderer): ReactTestInstance {
return mounted.root.findAll(
(node) =>
@@ -132,31 +117,6 @@ describe('MobileNativeChatBackgroundTasks', () => {
)
}
it('stops one row by its provider id and holds its button while the Stop is on its way', async () => {
let finish: (result: StopResult) => void = () => {}
const stop = vi.fn(() => new Promise<StopResult>((resolve) => (finish = resolve)))
const mounted = mount(
tasksFor(
{
state: 'monitoring',
supportsTaskStop: true,
children: [view('a'), view('b', { stoppable: false })]
},
{ stop }
)
)
expand(mounted)
const buttons = stopButtons(mounted)
expect(buttons.map((button) => button.props.accessibilityLabel)).toEqual(['Stop review a'])
act(() => buttons[0]!.props.onPress())
act(() => buttons[0]!.props.onPress())
expect(stop).toHaveBeenCalledTimes(1)
expect(stop).toHaveBeenCalledWith('task-a')
expect(stopButtons(mounted)[0]!.props.disabled).toBe(true)
await act(async () => finish(UNCONFIRMED))
expect(stopButtons(mounted)[0]!.props.disabled).toBe(false)
})
it('keeps a confirmed Stop held until its row leaves, and offers it again if the row comes back', async () => {
let finish: (result: StopResult) => void = () => {}
const stop = vi.fn(() => new Promise<StopResult>((resolve) => (finish = resolve)))
@@ -206,30 +166,4 @@ describe('MobileNativeChatBackgroundTasks', () => {
})
expect(stopButtons(mounted)[0]!.props.disabled).toBe(false)
})
it('offers Stop all only to a host with no per-row stop that still accepts one', async () => {
let finish: (result: StopResult) => void = () => {}
const stop = vi.fn(() => new Promise<StopResult>((resolve) => (finish = resolve)))
const fallback = mount(tasksFor({ state: 'monitoring', children: [view('a')] }, { stop }))
expand(fallback)
expect(stopButtons(fallback).map((button) => button.props.accessibilityLabel)).toEqual([
'Stop background tasks'
])
const button = stopButtons(fallback)[0]!
expect(styleOf(button)).toMatchObject({ minHeight: 32, minWidth: 44 })
expect(button.props.hitSlop).toBe(6)
expect(Number(styleOf(button).minHeight) + 2 * button.props.hitSlop).toBe(44)
act(() => button.props.onPress())
act(() => button.props.onPress())
expect(stop).toHaveBeenCalledTimes(1)
expect(stop).toHaveBeenCalledWith(undefined)
expect(stopButtons(fallback)[0]!.props.disabled).toBe(true)
await act(async () => finish(STOPPED))
expect(stopButtons(fallback)[0]!.props.disabled).toBe(false)
const none = mount(
tasksFor({ state: 'monitoring', supportsStopAll: false, children: [view('a')] })
)
expand(none)
expect(stopButtons(none)).toEqual([])
})
})
@@ -1,56 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
mobileNativeChatQuestionOffsets,
scheduleMobileClaudeAnswer,
MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS,
MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS
} from './mobile-native-chat-answer-stepping'
describe('mobileNativeChatQuestionOffsets', () => {
it('paces each question a full step apart, Enter 500ms after its body', () => {
expect(mobileNativeChatQuestionOffsets(0)).toEqual({ bodyAt: 0, enterAt: 500 })
expect(mobileNativeChatQuestionOffsets(1)).toEqual({ bodyAt: 1000, enterAt: 1500 })
expect(mobileNativeChatQuestionOffsets(2)).toEqual({ bodyAt: 2000, enterAt: 2500 })
})
})
describe('scheduleMobileClaudeAnswer', () => {
beforeEach(() => vi.useFakeTimers())
afterEach(() => vi.useRealTimers())
it('writes each question body then its Enter, paced per step, one Enter per line', () => {
const events: string[] = []
const timers = scheduleMobileClaudeAnswer(
['', 'b', 'c'],
(line) => events.push(`body:${line}`),
() => events.push('enter')
)
expect(timers).toHaveLength(6)
vi.advanceTimersByTime(0)
expect(events).toEqual(['body:'])
vi.advanceTimersByTime(MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS - 1)
expect(events).toEqual(['body:'])
vi.advanceTimersByTime(1)
expect(events).toEqual(['body:', 'enter'])
vi.advanceTimersByTime(MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS)
expect(events).toEqual(['body:', 'enter', 'body:b'])
vi.runAllTimers()
expect(events).toEqual(['body:', 'enter', 'body:b', 'enter', 'body:c', 'enter'])
})
it('cancelling the returned timers stops all pending writes', () => {
const events: string[] = []
const timers = scheduleMobileClaudeAnswer(
['a', 'b'],
(line) => events.push(`body:${line}`),
() => events.push('enter')
)
for (const timer of timers) {
clearTimeout(timer)
}
vi.runAllTimers()
expect(events).toEqual([])
})
})
@@ -1,13 +0,0 @@
import {
nativeChatQuestionOffsets,
scheduleNativeChatAnswer,
NATIVE_CHAT_ADVANCE_BUFFER_MS,
NATIVE_CHAT_QUESTION_STEP_MS,
NATIVE_CHAT_SUBMIT_DELAY_MS
} from '../../../../../src/shared/native-chat/input/native-chat-answer-stepping'
export const MOBILE_NATIVE_CHAT_ADVANCE_BUFFER_MS = NATIVE_CHAT_ADVANCE_BUFFER_MS
export const MOBILE_NATIVE_CHAT_QUESTION_STEP_MS = NATIVE_CHAT_QUESTION_STEP_MS
export const MOBILE_NATIVE_CHAT_SUBMIT_DELAY_MS = NATIVE_CHAT_SUBMIT_DELAY_MS
export const mobileNativeChatQuestionOffsets = nativeChatQuestionOffsets
export const scheduleMobileClaudeAnswer = scheduleNativeChatAnswer
@@ -1,261 +0,0 @@
// A structured Claude chat on the desktop, read back with `agentSession.history` after its owner
// approved a Bash call and answered an AskUserQuestion (Claude Code 2.1.300, 2026-10-15).
import type { AgentJournalRenderItem } from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
export const ANSWERED_PROMPT_ITEMS: AgentJournalRenderItem[] = [
{
itemId: 'orca:1792024009236-87ed41e5430c47008ef7978ca5d60505',
revision: 0,
body: {
kind: 'message',
role: 'user',
blocks: [
{
type: 'text',
text: 'Run the bash command: echo receipt-check > receipt.txt'
}
]
},
sequence: 43,
observedAt: 1792024010442,
turnScope: {
kind: 'thread'
}
},
{
itemId:
'orca:claude-tool%3A2ee61cec-1207-4f44-a915-b6adbcbf169b%3Atoolu_01FhhC72BuRiD3d9hXkAsURD',
revision: 2,
body: {
kind: 'tool-call',
name: 'Bash',
input: {
command: 'echo receipt-check > receipt.txt',
description: 'Write receipt-check to receipt.txt'
},
callId: 'toolu_01FhhC72BuRiD3d9hXkAsURD',
state: 'completed',
output: {
head: '(Bash completed with no output)',
byteLength: 31,
digest: 'cac1685585590361647e7a27b58a25a590f335bfcd0ab70fcdc0424e40c20843',
truncated: false
}
},
sequence: 46,
observedAt: 1792024014854,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d'
}
},
{
itemId:
'orca:claude-prompt%3Aclaude_c65b4304_2acf_4eec_a749_e06876328e0c%3A79c45210-730e-482c-82bd-db0708c992e5',
revision: 2,
body: {
kind: 'approval',
title: 'Allow Bash?',
displayName: 'Bash',
description: 'Write receipt-check to receipt.txt',
blockedPath: '/private/tmp/mnw-scratch/receipt.txt',
detail:
'{\n "command": "echo receipt-check > receipt.txt",\n "description": "Write receipt-check to receipt.txt"\n}',
options: [
{
id: 'allow',
label: 'Allow'
},
{
id: 'allowForSession',
label: 'Allow for this session'
},
{
id: 'deny',
label: 'Deny'
}
],
resolution: {
state: 'resolved',
selectedOptionId: 'allow',
resolvedBy: 'desktop-renderer',
resolvedAt: 1792024037937
}
},
sequence: 48,
observedAt: 1792024014910,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d'
}
},
{
itemId: 'claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:4408cf7b-bbe2-4a5d-aa80-6471db6d9c18',
revision: 2,
body: {
kind: 'message',
role: 'assistant',
blocks: [
{
type: 'text',
text: 'I ran the command. `receipt.txt` in `/private/tmp/mnw-scratch` now holds the line `receipt-check`.'
}
]
},
sequence: 51,
observedAt: 1792024040901,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A6a80bc01-4be4-466f-bd98-5cae8368ed1d'
}
},
{
itemId: 'orca:1792024048049-e58989ce33eb411a970225d03d2e4a18',
revision: 0,
body: {
kind: 'message',
role: 'user',
blocks: [
{
type: 'text',
text: 'Use the AskUserQuestion tool to ask me whether I prefer tea or coffee, then reply with my answer in one short sentence.'
}
]
},
sequence: 57,
observedAt: 1792024048075,
turnScope: {
kind: 'thread'
}
},
{
itemId:
'orca:claude-tool%3A2ee61cec-1207-4f44-a915-b6adbcbf169b%3Atoolu_01WByTgphD4HFByq9zPKXn2J',
revision: 2,
body: {
kind: 'tool-call',
name: 'AskUserQuestion',
input: {
questions: [
{
question: 'Do you prefer tea or coffee?',
header: 'Drink',
multiSelect: false,
options: [
{
label: 'Tea',
description: 'You prefer tea.'
},
{
label: 'Coffee',
description: 'You prefer coffee.'
}
]
}
]
},
callId: 'toolu_01WByTgphD4HFByq9zPKXn2J',
state: 'completed',
output: {
head: 'Your questions have been answered: "Do you prefer tea or coffee?"="Coffee". You can now continue with these answers in mind.',
byteLength: 124,
digest: '65dfb0af315c9ab1c70fc26c6c6bfb4ef0138216e35c89cf332927d10cbb629d',
truncated: false
}
},
sequence: 60,
observedAt: 1792024052205,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60'
}
},
{
itemId:
'orca:claude-prompt%3Aclaude_c65b4304_2acf_4eec_a749_e06876328e0c%3A6fd8be6a-830f-44b4-a3ef-a7f044cd4a4f',
revision: 2,
body: {
kind: 'question',
question: 'Do you prefer tea or coffee?',
options: [
{
id: 'q1:choice-1',
label: 'Tea',
description: 'You prefer tea.'
},
{
id: 'q1:choice-2',
label: 'Coffee',
description: 'You prefer coffee.'
}
],
freeTextQuestionId: 'q1',
questions: [
{
id: 'q1',
question: 'Do you prefer tea or coffee?',
header: 'Drink',
multiSelect: false,
options: [
{
id: 'q1:choice-1',
label: 'Tea',
description: 'You prefer tea.'
},
{
id: 'q1:choice-2',
label: 'Coffee',
description: 'You prefer coffee.'
}
],
freeTextQuestionId: 'q1'
}
],
resolution: {
state: 'resolved',
selectedOptionId: 'question-group:[{"questionId":"q1","optionIds":["q1:choice-2"]}]',
answers: [
{
questionId: 'q1',
optionIds: ['q1:choice-2']
}
],
resolvedBy: 'desktop-renderer',
resolvedAt: 1792024081980
}
},
sequence: 62,
observedAt: 1792024052228,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60'
}
},
{
itemId: 'claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:32c8a879-b68c-41ba-9a9e-4b844fa07890',
revision: 2,
body: {
kind: 'message',
role: 'assistant',
blocks: [
{
type: 'text',
text: 'You prefer coffee.'
}
]
},
sequence: 65,
observedAt: 1792024084176,
turnScope: {
kind: 'turn',
turnItemId:
'legacy:claude:2ee61cec-1207-4f44-a915-b6adbcbf169b:turn-lifecycle%3A1ea7cf09-10c6-4635-93bb-8d4b16fb1c60'
}
}
]
@@ -8,7 +8,7 @@ import {
import type { AskAnswerSelection } from '../../../../../src/shared/native-chat/input/native-chat-ask-answer'
import type { AskPrompt } from '../../../../../src/shared/native-chat/input/native-chat-ask-types'
import type { RpcClient } from '../../../transport/rpc/rpc-client-contract'
import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping'
import { NATIVE_CHAT_QUESTION_STEP_MS } from '../../../../../src/shared/native-chat/input/native-chat-answer-stepping'
import {
openMobileNativeChatSendBudget,
sendMobileNativeChatMessageWithOutcome
@@ -229,11 +229,11 @@ export function useMobileNativeChatAnswerSend(args: {
return fail()
}
if (index < groups.length - 1) {
if (!(await wait(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS))) {
if (!(await wait(NATIVE_CHAT_QUESTION_STEP_MS))) {
return false
}
// Pacing is deliberate, not transport latency — don't charge it to the budget.
deadline += MOBILE_NATIVE_CHAT_QUESTION_STEP_MS
deadline += NATIVE_CHAT_QUESTION_STEP_MS
}
}
return groups.length > 0 && writeTurnsRef.current.get(handle) === turn
@@ -1,107 +0,0 @@
// One phone chat view serves every chat tab, so returning to a chat must not wait on its next read.
import { act } from 'react-test-renderer'
import { expect, it } from 'vitest'
import type { AgentSessionOptionsResult } from '../../../../../src/shared/agent-session/options/agent-session-options-result'
import {
BASE,
OPTIONS,
accepted,
currentValueOf,
deferred,
mountOptions,
optionsClient,
recordingMutate,
settle
} from './use-mobile-structured-agent-options.test-fixture'
const COMMAND = 'compact'
const CHAT_A: AgentSessionOptionsResult = {
...OPTIONS,
acceptsImages: true,
conversationCommands: [COMMAND],
current: {
model: 'gpt-fast',
effort: 'low',
permissionMode: 'own',
reportedPermissionMode: 'ask',
acceptedInputSources: { model: 'saved', effort: 'saved' }
}
}
const CHAT_B: AgentSessionOptionsResult = {
...OPTIONS,
acceptsImages: false,
current: { model: 'gpt-live', effort: 'high', permissionMode: 'ask' }
}
/** Host replies per chat; later reads for chat A wait until the test answers them. */
function chats() {
const later: ReturnType<typeof deferred<AgentSessionOptionsResult>>[] = []
let readsOfA = 0
let readingB = false
const client = optionsClient(() => {
if (readingB) {
return Promise.resolve(CHAT_B)
}
if (readsOfA++ === 0) {
return Promise.resolve(CHAT_A)
}
const reply = deferred<AgentSessionOptionsResult>()
later.push(reply)
return reply.promise
})
const send = client.client.sendRequest
client.client.sendRequest = (method, params, options) => {
if (method === 'agentSession.options') {
readingB = JSON.stringify(params).includes('chat-b')
}
return send(method, params, options)
}
return { client, later }
}
it("shows a chat's last answer on return, without its reports, until its new read lands", async () => {
const { client, later } = chats()
const { mutate } = recordingMutate(async () => accepted({ key: 'model', value: 'x' }, true))
const harness = await mountOptions({
...BASE,
sessionId: 'chat-a',
fence: 1,
client: client.client,
mutate,
permissionOwn: true,
sendSelection: true
})
await harness.rerender({ sessionId: 'chat-b', fence: 7 })
expect(currentValueOf(harness.current().optionSnapshot, 'model')).toBe('gpt-live')
const commitsOnB = harness.commits.length
await harness.rerender({ sessionId: 'chat-a', fence: 2 })
expect(later).toHaveLength(1)
// From the first commit on return, not only after a later effect catches up.
for (const commit of harness.commits.slice(commitsOnB)) {
expect(currentValueOf(commit.optionSnapshot, 'model')).toBe('gpt-fast')
}
const shown = harness.current()
expect(currentValueOf(shown.optionSnapshot, 'model')).toBe('gpt-fast')
expect(currentValueOf(shown.optionSnapshot, 'effort')).toBe('low')
expect(shown.conversationCommands).toEqual([COMMAND])
expect(shown.acceptsImages).toBe(true)
// Saved permission intent survives a restart independently of runtime reports.
expect(currentValueOf(shown.optionSnapshot, 'permissionMode')).toBe('own')
expect(shown.sendSelection()).toEqual({ selection: {} })
await act(async () => {
later[0].resolve({
...CHAT_A,
conversationCommands: [],
current: { ...CHAT_A.current, model: 'gpt-live' }
})
})
await settle()
const answered = harness.current()
expect(currentValueOf(answered.optionSnapshot, 'model')).toBe('gpt-live')
expect(currentValueOf(answered.optionSnapshot, 'permissionMode')).toBe('own')
expect(answered.conversationCommands).toEqual([])
expect(answered.sendSelection()).toEqual({ selection: { model: 'gpt-live', effort: 'low' } })
await harness.unmount()
})
@@ -1,24 +0,0 @@
import { describe, expect, it } from 'vitest'
import { diffFromText } from '../../../../src/shared/native-chat/tools/native-chat-diff'
describe('diffFromText', () => {
it('caps large diffs before creating render rows', () => {
const text = Array.from(
{ length: 1_000 },
(_unused, index) => `${index % 2 === 0 ? '+' : '-'}line-${index}`
).join('\n')
const lines = diffFromText(text)
expect(lines).toHaveLength(120)
expect(lines?.at(-1)).toEqual({ kind: 'meta', text: '… diff truncated …' })
})
it('honors a smaller caller-owned aggregate row budget', () => {
const text = Array.from(
{ length: 100 },
(_unused, index) => `${index % 2 === 0 ? '+' : '-'}line-${index}`
).join('\n')
expect(diffFromText(text, 20)).toHaveLength(20)
})
})
@@ -1,49 +0,0 @@
import { describe, expect, it } from 'vitest'
import { mergeNativeChatMessages } from '../../../../src/shared/native-chat/native-chat-merge'
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
function msg(id: string, overrides: Partial<NativeChatMessage> = {}): NativeChatMessage {
return {
id,
role: 'assistant',
blocks: [{ type: 'text', text: id }],
timestamp: 0,
source: 'transcript',
...overrides
}
}
describe('mergeNativeChatMessages', () => {
it('appends new ids in arrival order', () => {
const merged = mergeNativeChatMessages([msg('a')], [msg('b'), msg('c')])
expect(merged.map((m) => m.id)).toEqual(['a', 'b', 'c'])
})
it('replaces a re-emitted id in place without reordering', () => {
const merged = mergeNativeChatMessages(
[msg('a'), msg('b'), msg('c')],
[msg('b', { blocks: [{ type: 'text', text: 'updated' }] })]
)
expect(merged.map((m) => m.id)).toEqual(['a', 'b', 'c'])
expect(merged[1]!.blocks).toEqual([{ type: 'text', text: 'updated' }])
})
it('does not let a lower-priority source overwrite a higher one', () => {
const merged = mergeNativeChatMessages(
[msg('a', { source: 'transcript', blocks: [{ type: 'text', text: 'real' }] })],
[msg('a', { source: 'scrape', blocks: [{ type: 'text', text: 'scraped' }] })]
)
expect(merged[0]!.blocks).toEqual([{ type: 'text', text: 'real' }])
})
it('returns the existing array unchanged for an empty batch', () => {
const existing = [msg('a')]
expect(mergeNativeChatMessages(existing, [])).toBe(existing)
})
it('does not mutate the existing array', () => {
const existing = [msg('a')]
mergeNativeChatMessages(existing, [msg('b')])
expect(existing.map((m) => m.id)).toEqual(['a'])
})
})
@@ -1,67 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types'
import {
applyAppend,
createNativeChatMerger,
mergeNativeChatMessages,
replaceList
} from '../../../../src/shared/native-chat/native-chat-merge'
function msg(id: string, overrides: Partial<NativeChatMessage> = {}): NativeChatMessage {
return {
id,
role: 'assistant',
blocks: [{ type: 'text', text: id }],
timestamp: 0,
source: 'transcript',
...overrides
}
}
// Compare each adversarial prefix with the pure merger so cached indexes cannot diverge from a full rebuild.
describe('mobile stateful merger — oracle vs pure merge', () => {
const base = [msg('a'), msg('b', { source: 'hook' })]
const batches: NativeChatMessage[][] = [
[msg('c')],
[],
[msg('b', { source: 'transcript', blocks: [{ type: 'text', text: 'final' }] })],
[msg('b', { source: 'scrape' })],
[msg('a')],
[msg('d'), msg('e')]
]
it('matches the pure merge for every prefix', () => {
const merger = createNativeChatMerger()
replaceList(merger, base)
let pure = mergeNativeChatMessages(base, [])
expect(merger.list).toEqual(pure)
for (const batch of batches) {
const out = applyAppend(merger, batch)
pure = mergeNativeChatMessages(pure, batch)
expect(out).toEqual(pure)
}
})
it('keeps prior row identity on a pure tail append', () => {
const merger = createNativeChatMerger()
replaceList(merger, base)
const before = merger.list
const tail = msg('z')
const after = applyAppend(merger, [tail])
expect(after).not.toBe(before)
expect(after[0]).toBe(before[0])
expect(after[after.length - 1]).toBe(tail)
})
it('bounds live appends and rebuilds the cached indexes for the retained tail', () => {
const merger = createNativeChatMerger()
replaceList(merger, [msg('a'), msg('b'), msg('c')])
expect(applyAppend(merger, [msg('d'), msg('e')], 3).map((m) => m.id)).toEqual(['c', 'd', 'e'])
expect(merger.indexById.has('a')).toBe(false)
expect(merger.indexById.get('c')).toBe(0)
expect(
applyAppend(merger, [msg('d', { blocks: [{ type: 'text', text: 'updated' }] })], 3)[1]
).toMatchObject({ id: 'd', blocks: [{ type: 'text', text: 'updated' }] })
})
})
@@ -1,147 +0,0 @@
import { createElement, type ReactNode } from 'react'
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AppStateStatus } from 'react-native'
const appState = vi.hoisted(() => ({
current: 'active',
listeners: new Set<(state: AppStateStatus) => void>()
}))
vi.mock('react-native', async () => {
const React = await import('react')
const Text = ({ children, ...props }: { children?: ReactNode }): unknown =>
React.createElement('Text', props, children)
return {
AppState: {
get currentState() {
return appState.current
},
addEventListener: (_event: string, listener: (state: AppStateStatus) => void) => {
appState.listeners.add(listener)
return {
remove: () => {
appState.listeners.delete(listener)
}
}
}
},
ActivityIndicator: (props: Record<string, unknown>) =>
React.createElement('ActivityIndicator', props),
Pressable: ({ children, ...props }: { children?: ReactNode }) =>
React.createElement('Pressable', props, children),
Text,
View: ({ children, ...props }: { children?: ReactNode }) =>
React.createElement('View', props, children),
StyleSheet: { create: (styles: unknown) => styles, hairlineWidth: 1 }
}
})
vi.mock('lucide-react-native', () => ({ ChevronRight: 'ChevronRight' }))
import { MobileNativeChatTurnStatus } from './MobileNativeChatTurnStatus'
import { findAllByHostType } from '../../../test-support/react-test-renderer-host-nodes'
const labels = (node: ReactTestInstance): string[] =>
findAllByHostType(node, 'Text').map((text) => String(text.children.join('')))
let renderer: ReactTestRenderer | null = null
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-09-04T00:00:00Z'))
appState.current = 'active'
appState.listeners.clear()
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
vi.restoreAllMocks()
vi.useRealTimers()
})
describe('MobileNativeChatTurnStatus', () => {
function changeAppState(state: AppStateStatus) {
act(() => {
appState.current = state
for (const listener of appState.listeners) {
listener(state)
}
})
}
function render(props: {
startedAt: number | null
workedSeconds?: number | null
verdict?: 'interruption' | 'cancellation'
expanded?: boolean
onToggleExpanded?: () => void
}): ReactTestRenderer {
act(() => {
renderer = create(createElement(MobileNativeChatTurnStatus, props))
})
return renderer!
}
it('stops clock callbacks in the background and catches up immediately on resume', () => {
const tree = render({ startedAt: Date.now() })
act(() => {
vi.advanceTimersByTime(2_000)
})
expect(labels(tree.root)).toEqual(['Working for 2s'])
changeAppState('background')
const clockReads = vi.spyOn(Date, 'now')
act(() => {
vi.advanceTimersByTime(60_000)
})
expect(clockReads).not.toHaveBeenCalled()
expect(vi.getTimerCount()).toBe(0)
expect(labels(tree.root)).toEqual(['Working for 2s'])
changeAppState('active')
expect(labels(tree.root)).toEqual(['Working for 1m 2s'])
expect(vi.getTimerCount()).toBe(1)
act(() => {
vi.advanceTimersByTime(1_000)
})
expect(labels(tree.root)).toEqual(['Working for 1m 3s'])
})
it('keeps the original pre-stamp epoch through background and settlement transitions', () => {
const tree = render({ startedAt: null })
act(() => {
vi.advanceTimersByTime(3_000)
})
expect(labels(tree.root)).toEqual(['Working for 3s'])
changeAppState('background')
act(() => {
vi.advanceTimersByTime(10_000)
})
act(() =>
tree.update(createElement(MobileNativeChatTurnStatus, { startedAt: null, workedSeconds: 8 }))
)
changeAppState('active')
expect(labels(tree.root)).toEqual(['Worked for 8s'])
expect(vi.getTimerCount()).toBe(0)
act(() => tree.update(createElement(MobileNativeChatTurnStatus, { startedAt: null })))
expect(labels(tree.root)).toEqual(['Working for 13s'])
expect(vi.getTimerCount()).toBe(1)
act(() => tree.unmount())
expect(vi.getTimerCount()).toBe(0)
expect(appState.listeners.size).toBe(0)
})
it('creates no clock while initially backgrounded and uses a supplied start time on resume', () => {
appState.current = 'background'
const startedAt = Date.now() - 5_000
const tree = render({ startedAt })
expect(vi.getTimerCount()).toBe(0)
act(() => {
vi.advanceTimersByTime(15_000)
})
changeAppState('active')
expect(labels(tree.root)).toEqual(['Working for 20s'])
expect(vi.getTimerCount()).toBe(1)
})
})
@@ -63,15 +63,11 @@ vi.mock('lucide-react-native', () => ({
Wrench: 'Wrench',
Terminal: 'Terminal'
}))
const proseRenders = vi.hoisted(() => ({ count: 0 }))
export function proseRenderCount() {
return proseRenders.count
}
vi.mock('../../../components/MobileMarkdown', async () => {
const React = await import('react')
return {
MobileMarkdown: (props: ComponentProps<typeof MobileMarkdownComponent>) => {
proseRenders.count++
return React.createElement('MobileMarkdown', props)
}
}
@@ -0,0 +1,62 @@
import { describe, expect, it } from 'vitest'
import {
createNativeChatMerger,
replaceList
} from '../../../../../src/shared/native-chat/native-chat-merge'
import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types'
import { applyMobileNativeChatStreamFrame } from './mobile-native-chat-stream-frame'
function message(id: string): NativeChatMessage {
return {
id,
role: 'assistant',
blocks: [{ type: 'text', text: id }],
timestamp: 0,
source: 'transcript'
}
}
describe('applyMobileNativeChatStreamFrame', () => {
it('replaces a partially overlapping replay that no longer extends the retained tail', () => {
const merger = createNativeChatMerger()
replaceList(merger, ['old-1', 'shared', 'old-tail'].map(message))
// Keep hasMore true so only the contiguity check can reject the interleaved row.
const replay = [message('shared'), message('compacted-summary'), message('old-tail')]
expect(
applyMobileNativeChatStreamFrame({
merger,
frame: { type: 'snapshot', messages: replay, hasMore: true, beforeOffset: 9 },
limit: 100,
replaceSnapshot: false
})
).toEqual({
kind: 'messages',
messages: replay,
hasMore: true,
beforeOffset: 9,
windowReplaced: true
})
})
it('replaces retained history when replay metadata says no earlier rows remain', () => {
const merger = createNativeChatMerger()
replaceList(merger, ['removed-1', 'removed-2', 'a', 'b'].map(message))
const replay = [message('a'), message('b')]
expect(
applyMobileNativeChatStreamFrame({
merger,
frame: { type: 'snapshot', messages: replay, hasMore: false, beforeOffset: 0 },
limit: 100,
replaceSnapshot: false
})
).toEqual({
kind: 'messages',
messages: replay,
hasMore: false,
beforeOffset: 0,
windowReplaced: true
})
})
})
@@ -1,47 +0,0 @@
import { describe, expect, it, vi } from 'vitest'
import type { SupportedUiLocale } from '../../../../../src/shared/ui-locale'
import {
joinNativeChatToolRunClauses,
nativeChatToolRunSentence
} from '../../../../../src/shared/native-chat/tools/native-chat-tool-run-sentence'
import { getMobileUiLocale } from '../../../i18n/mobile-i18n'
import { nativeChatToolRunWords } from './native-chat-tool-run-words'
vi.mock('../../../i18n/mobile-i18n', () => ({
getMobileUiLocale: vi.fn(() => 'en')
}))
const joiners = {
pair: (first: string, second: string) => `${first} | ${second}`,
list: (leading: readonly string[], last: string) => [...leading, last].join(' | ')
}
function mobileWords(locale: SupportedUiLocale) {
vi.mocked(getMobileUiLocale).mockReturnValue(locale)
return { ...nativeChatToolRunWords((_key, fallback) => fallback), ...joiners }
}
describe('mobile tool-run sentence continuations', () => {
it('keeps German noun capitalization through the sentence formatter', () => {
const words = mobileWords('de')
expect(
nativeChatToolRunSentence(
[
{ type: 'tool-call', name: 'read', input: {} },
{ type: 'tool-call', name: 'Bash', input: { command: 'orca snapshot --page p1' } }
],
{},
{
...words,
clause: (category) => (category === 'browser' ? 'Browser verwendet' : 'Datei gelesen')
}
)
).toBe('Datei gelesen | Browser verwendet')
})
it('uses Turkish casing for both dotted and dotless I in later clauses', () => {
expect(joinNativeChatToolRunClauses(['Başladı', 'İnceledi', 'Isındı'], mobileWords('tr'))).toBe(
'Başladı | inceledi | ısındı'
)
})
})
@@ -1,87 +0,0 @@
import { expect, it } from 'vitest'
import { nativeChatTurnDrawOrder } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-grouping'
import { nativeChatTurnMembership } from '../../../../../src/shared/native-chat/transcript/native-chat-turn-membership'
import type {
AgentJournalItemBody,
AgentJournalRenderItem
} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
it.each([10, 100])(
'reads turn ownership linearly for %i queued openers and earlier-turn rows',
(count) => {
const messages = [
{ id: 'first', role: 'user' as const },
...Array.from({ length: count }, (_, index) => ({
id: `queued-${index}`,
role: 'user' as const
})),
...Array.from({ length: count }, (_, index) => ({
id: `tail-${index}`,
role: 'assistant' as const
})),
...Array.from({ length: count }, (_, index) => ({
id: `answer-${index}`,
role: 'assistant' as const
}))
]
const keys = [
'first',
...Array.from({ length: count }, (_, index) => `queued-${index}`),
...Array.from({ length: count }, () => 'first'),
...Array.from({ length: count }, (_, index) => `queued-${index}`)
]
const openers = new Set(keys.slice(0, count + 1))
let reads = 0
keys.forEach((key, index) => {
Object.defineProperty(keys, index, {
get: () => {
reads += 1
return key
}
})
})
const order = nativeChatTurnDrawOrder(messages, keys, openers)
const visits = reads
expect(order?.map((index) => messages[index]?.id)).toEqual([
'first',
...Array.from({ length: count }, (_, index) => `tail-${index}`),
...Array.from({ length: count }, (_, index) => [`queued-${index}`, `answer-${index}`]).flat()
])
const journalItems: AgentJournalRenderItem[] = []
const append = (itemId: string, body: AgentJournalItemBody, turnItemId: string) => {
const sequence = journalItems.length + 1
journalItems.push({
itemId,
body,
revision: 0,
sequence,
observedAt: sequence,
turnScope: { kind: 'turn', turnItemId }
})
}
append('first', { kind: 'message', role: 'user', blocks: [] }, 'turn-first')
append(
'turn-first',
{ kind: 'turn', turnId: 'first', state: 'completed', userItemId: 'first' },
'turn-first'
)
for (let index = 0; index < count; index += 1) {
append(`queued-${index}`, { kind: 'message', role: 'user', blocks: [] }, `turn-${index}`)
}
for (let index = 0; index < count; index += 1) {
append(`tail-${index}`, { kind: 'message', role: 'assistant', blocks: [] }, 'turn-first')
}
for (let index = 0; index < count; index += 1) {
append(
`turn-${index}`,
{ kind: 'turn', turnId: `t${index}`, state: 'completed', userItemId: `queued-${index}` },
`turn-${index}`
)
append(`answer-${index}`, { kind: 'message', role: 'assistant', blocks: [] }, `turn-${index}`)
}
const membership = nativeChatTurnMembership(messages, { items: journalItems, submissions: [] })
expect(membership.turnKeys).toEqual(keys)
expect(membership.drawOrder).toEqual(order)
expect(visits).toBeLessThanOrEqual(messages.length * 4)
}
)
@@ -1,80 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type {
AgentJournalRenderItem,
AgentJournalSubmission,
AgentJournalTurnLifecycle
} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types'
import { agentJournalTurnBody } from '../../../../../src/shared/agent-session/lifecycle/agent-session-turn-record'
import { useMobileStructuredAgentTurnTiming } from './use-mobile-structured-agent-turn-timing'
// Skew the host clock by an hour so unconverted timestamp leakage is obvious.
const HOST_START = 3_600_000_000
const CLIENT_NOW = 12_345_000
function user(itemId: string, sequence: number): AgentJournalRenderItem {
return {
itemId,
revision: 0,
sequence,
observedAt: HOST_START + sequence,
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: itemId }] }
}
}
function lifecycle(
turnId: string,
sequence: number,
turn: Omit<AgentJournalTurnLifecycle, 'turnId'>,
observedAt: number
): AgentJournalRenderItem {
return {
itemId: `lifecycle-${turnId}`,
revision: 1,
sequence,
observedAt,
body: agentJournalTurnBody({ turnId, ...turn })
}
}
type Timing = ReturnType<typeof useMobileStructuredAgentTurnTiming>
const NO_SUBMISSIONS: readonly AgentJournalSubmission[] = []
describe('useMobileStructuredAgentTurnTiming', () => {
let renderer: ReactTestRenderer | null = null
let timing: Timing | null = null
function Harness({
items,
submissions = NO_SUBMISSIONS,
turnId,
hostClock
}: {
items: readonly AgentJournalRenderItem[]
submissions?: readonly AgentJournalSubmission[]
turnId: string | null
hostClock?: { hostNow: number; receivedAt: number }
}): null {
timing = useMobileStructuredAgentTurnTiming({ items, submissions, hostClock }, turnId)
return null
}
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
timing = null
vi.useRealTimers()
})
it('leaves the anchor null when an older host records no start', () => {
vi.useFakeTimers()
vi.setSystemTime(CLIENT_NOW)
const items = [user('u1', 1), lifecycle('t1', 2, { state: 'running' }, HOST_START)]
act(() => {
renderer = create(createElement(Harness, { items, turnId: 't1' }))
})
expect(timing?.workingStartedAt).toBeNull()
expect(timing?.settledTurns.size).toBe(0)
})
})
@@ -5,19 +5,13 @@ import { useMobileNativeChatTerminalStream } from './use-mobile-native-chat-term
describe('useMobileNativeChatTerminalStream', () => {
let renderer: ReactTestRenderer | null = null
let harnessRenderCount = 0
const subscriptionsRef = { current: new Map<string, () => void>() }
const subscribingRef = { current: new Set<string>() }
const leaseOnlyRef = { current: new Set<string>() }
const webReadyRef = { current: new Set(['terminal-1']) }
let subscribeOpensLeaseOnly = false
const registerSubscription = (handle: string): boolean => {
subscriptionsRef.current.set(handle, () => {})
if (subscribeOpensLeaseOnly) {
leaseOnlyRef.current.add(handle)
} else {
leaseOnlyRef.current.delete(handle)
}
leaseOnlyRef.current.delete(handle)
return true
}
const subscribe = vi.fn(registerSubscription)
@@ -25,7 +19,6 @@ describe('useMobileNativeChatTerminalStream', () => {
subscriptionsRef.current.delete(handle)
leaseOnlyRef.current.delete(handle)
})
const notifyWebReadyRef = { current: (_handle: string, _wasAlreadyReady: boolean): void => {} }
const notifyListedHandlesRef = { current: (_liveHandles: ReadonlySet<string>): void => {} }
const hasTabsRecoveryNeedRef = { current: (): boolean => false }
@@ -33,9 +26,7 @@ describe('useMobileNativeChatTerminalStream', () => {
subscriptionsRef.current = new Map([['terminal-1', () => {}]])
subscribingRef.current = new Set()
leaseOnlyRef.current = new Set()
subscribeOpensLeaseOnly = false
webReadyRef.current = new Set(['terminal-1'])
harnessRenderCount = 0
subscribe.mockClear()
unsubscribe.mockClear()
})
@@ -56,7 +47,6 @@ describe('useMobileNativeChatTerminalStream', () => {
leaseReady?: boolean
streamRevision?: number
}): null {
harnessRenderCount += 1
const stream = useMobileNativeChatTerminalStream({
showNativeChat,
activeHandle,
@@ -70,7 +60,6 @@ describe('useMobileNativeChatTerminalStream', () => {
subscribe,
unsubscribe
})
notifyWebReadyRef.current = stream.notifyWebReady
notifyListedHandlesRef.current = stream.notifyListedHandles
hasTabsRecoveryNeedRef.current = stream.hasTabsRecoveryNeed
return null
@@ -95,244 +84,6 @@ describe('useMobileNativeChatTerminalStream', () => {
})
}
// A synchronous tab switch still sees old chat coverage and opens the incoming terminal as lease-only.
function handOffToTerminalTwo(): void {
subscribeOpensLeaseOnly = true
subscribe('terminal-2')
subscribeOpensLeaseOnly = false
subscribe.mockClear()
unsubscribe.mockClear()
}
it('trades a lease-only stream for output when a chat tab hands off to a terminal tab', async () => {
webReadyRef.current.add('terminal-2')
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
handOffToTerminalTwo()
await act(async () => {
renderer?.update(
createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' })
)
})
expect(unsubscribe).toHaveBeenCalledWith('terminal-2')
expect(subscribe).toHaveBeenCalledWith('terminal-2')
expect(leaseOnlyRef.current.has('terminal-2')).toBe(false)
})
it('repairs a lease-only stream once its WebView reports ready', async () => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
handOffToTerminalTwo()
await act(async () => {
renderer?.update(
createElement(Harness, { showNativeChat: false, activeHandle: 'terminal-2' })
)
})
// A cold WebView must wait; its normal ready path skips already-live lease subscriptions.
expect(subscribe).not.toHaveBeenCalled()
await act(async () => {
webReadyRef.current.add('terminal-2')
notifyWebReadyRef.current('terminal-2', false)
})
expect(unsubscribe).toHaveBeenCalledWith('terminal-2')
expect(subscribe).toHaveBeenCalledWith('terminal-2')
})
it.each([true, false])(
'stops rearming a handle whose stream never comes back (covered: %s, #10681)',
async (showNativeChat) => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat }))
})
subscribe.mockClear()
// Dead PTYs answer subscribed/end repeatedly; rearm must stop rather than loop through host waits.
for (let revision = 1; revision <= 6; revision += 1) {
subscriptionsRef.current.delete('terminal-1')
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat,
leaseReady: false,
streamRevision: revision
})
)
})
}
expect(subscribe.mock.calls.length).toBeLessThanOrEqual(3)
}
)
it('does not charge the rearm budget for a subscribe its own gates turned away', async () => {
try {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
subscribe.mockClear()
// Locally rejected subscribes never reached the host and must not spend real attempts.
subscribe.mockImplementation(() => false)
for (let revision = 1; revision <= 5; revision += 1) {
subscriptionsRef.current.delete('terminal-1')
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat: true,
leaseReady: false,
streamRevision: revision
})
)
})
}
expect(subscribe).toHaveBeenCalledTimes(5)
} finally {
subscribe.mockImplementation(registerSubscription)
}
})
it('charges the rearm budget for a subscribe the bridge refused before returning', async () => {
try {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: false }))
})
subscribe.mockClear()
// A synchronous refusal ends the stream inside subscribe, so no ref ever shows it was sent.
subscribe.mockImplementation(() => true)
for (let revision = 1; revision <= 5; revision += 1) {
subscriptionsRef.current.delete('terminal-1')
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat: false,
leaseReady: false,
streamRevision: revision
})
)
})
}
expect(subscribe).toHaveBeenCalledTimes(3)
} finally {
subscribe.mockImplementation(registerSubscription)
}
})
it.each([true, false])(
'refills the rearm budget when terminal.list reports the handle again (covered: %s, #10681)',
async (showNativeChat) => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat }))
})
for (let revision = 1; revision <= 5; revision += 1) {
subscriptionsRef.current.delete('terminal-1')
await act(async () => {
renderer?.update(
createElement(Harness, {
showNativeChat,
leaseReady: false,
streamRevision: revision
})
)
})
}
subscribe.mockClear()
await act(async () => {
renderer?.update(
createElement(Harness, { showNativeChat, leaseReady: false, streamRevision: 6 })
)
})
expect(subscribe).not.toHaveBeenCalled()
// Still-listed dead handles must not refill on every inventory refresh.
await act(async () => {
notifyListedHandlesRef.current(new Set(['terminal-1']))
notifyListedHandlesRef.current(new Set(['terminal-1']))
})
expect(subscribe).not.toHaveBeenCalled()
await act(async () => {
notifyListedHandlesRef.current(new Set())
notifyListedHandlesRef.current(new Set(['terminal-1']))
})
expect(subscribe).toHaveBeenCalledWith('terminal-1')
}
)
it('does not let a dead PTY buy a new budget with its own `subscribed` ack', async () => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
subscribe.mockClear()
// Subscribed is only half a dead-PTY reply; clearing attempts there would refill the loop forever.
for (let revision = 1; revision <= 6; revision += 1) {
await playDeadPtyRoundTrip(revision)
}
expect(subscribe.mock.calls.length).toBeLessThanOrEqual(3)
})
it('refills the budget for a rearmed stream that outlives the teardown window', async () => {
vi.useFakeTimers()
try {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
subscribe.mockClear()
for (let revision = 1; revision <= 3; revision += 1) {
await playDeadPtyRoundTrip(revision)
}
expect(subscribe).toHaveBeenCalledTimes(3)
subscribe.mockClear()
subscriptionsRef.current.set('terminal-1', () => {})
await act(async () => {
renderer?.update(
createElement(Harness, { showNativeChat: true, leaseReady: true, streamRevision: 4 })
)
})
await act(async () => {
vi.advanceTimersByTime(5_000)
})
await playDeadPtyRoundTrip(5)
expect(subscribe).toHaveBeenCalledWith('terminal-1')
} finally {
vi.useRealTimers()
}
})
it('keeps an absence marker observed before the budget ran out', async () => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
for (let revision = 1; revision <= 2; revision += 1) {
await playDeadPtyRoundTrip(revision)
}
// Preserve absence markers until exhaustion actually consumes them; early consumption can permanently lock a still-listed handle.
await act(async () => {
notifyListedHandlesRef.current(new Set())
notifyListedHandlesRef.current(new Set(['terminal-1']))
})
await playDeadPtyRoundTrip(3)
subscribe.mockClear()
await playDeadPtyRoundTrip(4)
expect(subscribe).not.toHaveBeenCalled()
await act(async () => {
notifyListedHandlesRef.current(new Set(['terminal-1']))
})
expect(subscribe).toHaveBeenCalledWith('terminal-1')
})
it('keeps asking until a tab snapshot replaces the exhausted handle', async () => {
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
@@ -364,25 +115,4 @@ describe('useMobileNativeChatTerminalStream', () => {
})
expect(hasTabsRecoveryNeedRef.current()).toBe(false)
})
it('resumes a cold-start lease-only stream when WebView readiness arrives late', async () => {
webReadyRef.current.clear()
await act(async () => {
renderer = create(createElement(Harness, { showNativeChat: true }))
})
await act(async () => {
renderer?.update(createElement(Harness, { showNativeChat: false }))
})
expect(unsubscribe).toHaveBeenCalledOnce()
expect(subscribe).toHaveBeenCalledOnce()
webReadyRef.current.add('terminal-1')
await act(async () => {
notifyWebReadyRef.current('terminal-1', false)
})
expect(unsubscribe).toHaveBeenNthCalledWith(2, 'terminal-1')
expect(subscribe).toHaveBeenNthCalledWith(2, 'terminal-1')
})
})
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import '../../terminal/terminal-reply-schema'
import { sessionForwardedReplySchema } from '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../agent-launch/mobile-agent-detection-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../terminal/session/mobile-session-terminal-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../../files/workspace-file-paths-reply-schema'
// Leave replies raw until the controller’s generation, barrier and application-revision guards pass.
export const sessionTabsListRead = bindDeferredRpcOperation(
@@ -1,7 +1,5 @@
import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation'
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../../terminal/terminal-reply-schema'
import { sessionCreatedTerminalTabSchema } from '../../terminal/session/mobile-session-terminal-reply-schema'
import { sessionTabCloseReplySchema } from './mobile-session-tab-write-reply-schema'
@@ -1,5 +1,4 @@
import * as z from 'zod'
import '../../../../src/shared/zod-salvage'
// Bare legacy success and delegated closes do not prove permanent retirement.
export const sessionTabCloseReplySchema = z
@@ -1,12 +1,6 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { WorktreeShowResolution } from '../worktree/worktree-show-resolution'
import { describe, expect, it } from 'vitest'
import { isSyntheticWorkspaceRoute } from './synthetic-workspace-route'
import {
shouldBounceMissingWorktree,
useMissingWorktreeBounce
} from './use-missing-worktree-bounce'
import { shouldBounceMissingWorktree } from './use-missing-worktree-bounce'
describe('shouldBounceMissingWorktree', () => {
it('bounces only a host-proven missing worktree', () => {
@@ -21,60 +15,3 @@ describe('shouldBounceMissingWorktree', () => {
expect(shouldBounceMissingWorktree('global-floating-terminal', 'missing')).toBe(false)
})
})
describe('useMissingWorktreeBounce', () => {
let renderer: ReactTestRenderer | null = null
const bounce = vi.fn()
beforeEach(() => {
bounce.mockReset()
renderer = null
})
function Harness(props: { worktreeId: string; resolution: WorktreeShowResolution }): null {
useMissingWorktreeBounce({
hostId: 'host-1',
worktreeId: props.worktreeId,
resolution: props.resolution,
bounce
})
return null
}
function render(worktreeId: string, resolution: WorktreeShowResolution): void {
act(() => {
const element = createElement(Harness, { worktreeId, resolution })
if (renderer) {
renderer.update(element)
} else {
renderer = create(element)
}
})
}
it('bounces exactly once per worktree even across re-renders', () => {
render('repo::wt', 'unknown')
expect(bounce).not.toHaveBeenCalled()
render('repo::wt', 'missing')
expect(bounce).toHaveBeenCalledExactlyOnceWith('host-1')
// Why: navigation lands after the render, so the pre-unmount renders must not re-fire.
render('repo::wt', 'missing')
render('repo::wt', 'unknown')
render('repo::wt', 'missing')
expect(bounce).toHaveBeenCalledTimes(1)
act(() => renderer?.unmount())
})
it('re-arms for a different worktree on the reused screen', () => {
render('repo::wt-1', 'missing')
expect(bounce).toHaveBeenCalledTimes(1)
render('repo::wt-2', 'unknown')
expect(bounce).toHaveBeenCalledTimes(1)
render('repo::wt-2', 'missing')
expect(bounce).toHaveBeenCalledTimes(2)
act(() => renderer?.unmount())
})
})
@@ -68,52 +68,6 @@ describe('useMobileDefaultSessionViewPreference', () => {
expect(saveDefaultSessionView).toHaveBeenCalledWith('chat')
})
it('submits every change immediately so shared persistence preserves event order', async () => {
const firstSave = deferred<void>()
vi.mocked(saveDefaultSessionView)
.mockImplementationOnce(() => firstSave.promise)
.mockResolvedValue(undefined)
await mount()
act(() => preference?.setDefaultView('chat'))
await act(async () => {
await Promise.resolve()
})
act(() => preference?.setDefaultView('terminal'))
act(() => preference?.setDefaultView('chat'))
await act(async () => {
await Promise.resolve()
})
expect(saveDefaultSessionView).toHaveBeenCalledTimes(3)
expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal')
expect(saveDefaultSessionView).toHaveBeenNthCalledWith(3, 'chat')
await act(async () => {
firstSave.resolve()
await firstSave.promise
await Promise.resolve()
})
expect(saveDefaultSessionView).toHaveBeenCalledTimes(3)
})
it('reloads the persisted value when the latest write fails', async () => {
vi.mocked(loadDefaultSessionView)
.mockResolvedValueOnce('terminal')
.mockResolvedValueOnce('terminal')
vi.mocked(saveDefaultSessionView).mockRejectedValue(new Error('storage unavailable'))
await mount()
await act(async () => {
preference?.setDefaultView('chat')
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
})
expect(preference?.defaultView).toBe('terminal')
expect(loadDefaultSessionView).toHaveBeenCalledTimes(2)
})
it('does not let an older failed write roll back a newer choice', async () => {
const recoveryLoad = deferred<MobileSessionView>()
vi.mocked(loadDefaultSessionView)
@@ -140,27 +94,4 @@ describe('useMobileDefaultSessionViewPreference', () => {
expect(preference?.defaultView).toBe('terminal')
expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal')
})
it('submits the latest write before the Settings route unmounts', async () => {
const firstSave = deferred<void>()
vi.mocked(saveDefaultSessionView)
.mockImplementationOnce(() => firstSave.promise)
.mockResolvedValueOnce(undefined)
await mount()
act(() => preference?.setDefaultView('chat'))
await act(async () => {
await Promise.resolve()
})
act(() => preference?.setDefaultView('terminal'))
expect(saveDefaultSessionView).toHaveBeenNthCalledWith(2, 'terminal')
act(() => renderer?.unmount())
renderer = null
await act(async () => {
firstSave.resolve()
await firstSave.promise
await Promise.resolve()
})
})
})
@@ -146,19 +146,6 @@ describe('useMobileSessionViewMode', () => {
expect(controller?.ready).toBe(true)
})
it('toggles from the effective view and persists the override', async () => {
await mount({ defaultView: 'chat' })
await act(async () => {
controller?.toggleTabChatView('t1')
await Promise.resolve()
})
expect(updateSessionViewOverride).toHaveBeenLastCalledWith('h', 'w', 't1', 'terminal')
expect(controller?.isTabChatView('t1')).toBe(false)
expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(1)
})
it('toggles a terminal-default tab into chat', async () => {
await mount({ defaultView: 'terminal' })
@@ -293,41 +280,6 @@ describe('useMobileSessionViewMode', () => {
})
})
it('submits rapid mutations in event order', async () => {
await mount({ defaultView: 'terminal' })
act(() => controller?.toggleTabChatView('t1'))
act(() => controller?.toggleTabChatView('t2'))
expect(updateSessionViewOverride).toHaveBeenNthCalledWith(1, 'h', 'w', 't1', 'chat')
expect(updateSessionViewOverride).toHaveBeenNthCalledWith(2, 'h', 'w', 't2', 'chat')
})
it('reconciles the latest optimistic override when persistence fails', async () => {
vi.mocked(updateSessionViewOverride).mockRejectedValue(new Error('storage unavailable'))
vi.mocked(readSessionViewOverridesPreference)
.mockResolvedValueOnce({
overrides: new Map<string, MobileSessionView>([['t1', 'terminal']]),
loaded: true
})
.mockResolvedValueOnce({
overrides: new Map<string, MobileSessionView>([['t1', 'terminal']]),
loaded: true
})
await mount({
defaultView: 'terminal',
overrides: new Map<string, MobileSessionView>([['t1', 'terminal']])
})
await act(async () => {
controller?.toggleTabChatView('t1')
await Promise.resolve()
await Promise.resolve()
})
expect(controller?.isTabChatView('t1')).toBe(false)
expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(2)
})
it('does not let an older failed override roll back a newer choice', async () => {
const recoveryLoad = deferred<Map<string, MobileSessionView>>()
vi.mocked(updateSessionViewOverride)
@@ -354,47 +306,6 @@ describe('useMobileSessionViewMode', () => {
expect(updateSessionViewOverride).toHaveBeenNthCalledWith(2, 'h', 'w', 't1', 'terminal')
})
it('fails closed when both an override write and its recovery read fail', async () => {
vi.mocked(loadDefaultSessionView).mockResolvedValue('chat')
vi.mocked(updateSessionViewOverride).mockRejectedValue(new Error('storage unavailable'))
vi.mocked(readSessionViewOverridesPreference)
.mockResolvedValueOnce({
overrides: new Map<string, MobileSessionView>([['t1', 'terminal']]),
loaded: true
})
.mockResolvedValueOnce({ overrides: new Map(), loaded: false })
await mount({
defaultView: 'chat',
overrides: new Map<string, MobileSessionView>([['t1', 'terminal']])
})
await act(async () => {
controller?.toggleTabChatView('t1')
await Promise.resolve()
await Promise.resolve()
})
expect(controller?.isTabChatView('t1')).toBe(false)
expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(2)
})
it('does not reload a failed override after the route unmounts', async () => {
const failedWrite = deferred<void>()
vi.mocked(updateSessionViewOverride).mockReturnValue(failedWrite.promise)
await mount({ defaultView: 'terminal' })
act(() => controller?.toggleTabChatView('t1'))
act(() => renderer?.unmount())
renderer = null
await act(async () => {
failedWrite.reject(new Error('storage unavailable'))
await Promise.resolve()
await Promise.resolve()
})
expect(readSessionViewOverridesPreference).toHaveBeenCalledTimes(1)
})
it('fails closed to terminal when overrides cannot be read under a chat default', async () => {
vi.mocked(loadDefaultSessionView).mockResolvedValue('chat')
vi.mocked(readSessionViewOverridesPreference).mockResolvedValue({
@@ -1,126 +0,0 @@
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 { FolderListRow } from './mobile-folder-attached-worktrees'
const seen = vi.hoisted(() => {
const state: { covered: boolean; membersObserving: boolean[]; rowsSubscribed: boolean[] } = {
covered: false,
membersObserving: [],
rowsSubscribed: []
}
return state
})
vi.mock('react-native', () => ({ ScrollView: 'ScrollView', View: 'View' }))
vi.mock('lucide-react-native', () => ({ GitBranch: 'GitBranch' }))
vi.mock('expo-router', () => ({ useFocusEffect: () => {} }))
vi.mock('react-native-safe-area-context', () => ({
SafeAreaView: 'SafeAreaView',
useSafeAreaInsets: () => ({ bottom: 0 })
}))
vi.mock('../../components/MobileStateView', () => ({
MobileLoadErrorState: 'MobileLoadErrorState',
MobileOfflineState: 'MobileOfflineState',
MobileStateView: 'MobileStateView'
}))
vi.mock('../../transport/connection/connection-retry-action', () => ({
connectionRetryAction: () => () => {}
}))
vi.mock('../../transport/connection/host-client-hooks', () => ({
useForceReconnect: () => () => {}
}))
vi.mock('../../components/bottom-drawer/BottomDrawer', () => ({
OptionPager: ({ main }: { main: ReactNode }) => main,
useOptionPager: () => ({ page: null, open: () => {}, close: () => {} })
}))
vi.mock('../../components/list/ListGroup', () => ({ ListGroup: 'ListGroup' }))
vi.mock('../../i18n/use-mobile-translation', () => ({
useMobileTranslation: () => (_key: string, fallback: string) => fallback
}))
vi.mock('../../navigation/use-back-claim', () => ({ useBackClaim: () => {} }))
vi.mock('../../navigation/workspace-route-handoff', () => ({
useWorkspaceRouteHandoff: () => ({ back: () => {} })
}))
vi.mock('../../navigation/workspace-route', () => ({
WorkspaceExecutionScope: 'WorkspaceExecutionScope'
}))
vi.mock('../../theme/mobile-theme', () => ({ colors: {}, spacing: { lg: 16 } }))
vi.mock('../../theme/themed-styles', () => ({
themedStyleSheet: (styles: () => unknown) => styles()
}))
vi.mock('../../theme/use-mobile-color-scheme', () => ({ useMobileColorScheme: () => {} }))
vi.mock('../MobileSourceControlHeader', () => ({
MobileSourceControlHeader: 'MobileSourceControlHeader'
}))
vi.mock('../MobileSourceControlPanel', () => ({ MobileSourceControlPanel: 'Panel' }))
vi.mock('../mobile-source-control-styles', () => ({ styles: {} }))
vi.mock('./MobileFolderEmptyState', () => ({ MobileFolderEmptyState: 'EmptyState' }))
vi.mock('../../components/host-protocol-gates-context', () => ({
useOptionalHostProtocolGates: () => null
}))
vi.mock('./use-folder-create-flow', () => ({
useFolderCreateFlow: () => ({
onCreate: async () => {},
covered: seen.covered,
composerElement: null,
toastElement: null
})
}))
vi.mock('./MobileFolderWorktreeRow', () => ({
MobileFolderWorktreeRow: (props: { subscribed: boolean }) => {
seen.rowsSubscribed.push(props.subscribed)
return null
}
}))
vi.mock('./use-mobile-folder-attached-worktrees', () => ({
useMobileFolderAttachedWorktrees: (_hostId: string, _folderId: string, observing: boolean) => {
seen.membersObserving.push(observing)
return {
folder: { worktreeId: 'folder:f-1', repoId: 'folder-workspace:f-1', displayName: 'payments' },
worktrees: [ROW],
desktopCapabilities: [],
serverHosts: [],
connState: 'connected',
loadError: null,
refetch: () => {}
}
}
}))
import { MobileFolderSourceControlPanel } from './MobileFolderSourceControlPanel'
const ROW: FolderListRow = {
worktreeId: 'repo-1::/w/payments',
repoId: 'repo-1',
repo: 'orca',
displayName: 'payments',
branch: 'payments'
}
let renderer: ReactTestRenderer | null = null
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
seen.covered = false
seen.membersObserving = []
seen.rowsSubscribed = []
})
describe('MobileFolderSourceControlPanel', () => {
it('pauses row status under the create form while the folder members stay live', () => {
seen.covered = true
act(() => {
renderer = create(
createElement(MobileFolderSourceControlPanel, {
hostId: 'host-1',
folderWorktreeId: 'folder:f-1',
name: 'payments',
embedded: true
})
)
})
expect(seen.rowsSubscribed.at(-1)).toBe(false)
expect(seen.membersObserving.at(-1)).toBe(true)
})
})
@@ -1,16 +1,6 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { stubRpcClient } from '../../transport/rpc/rpc-client-test-stub'
import { useHostQuery } from '../../query/host-query'
import { scopeRpcClientToExecutionHost } from '../../worktree/execution-host-scoped-rpc-client'
import {
documentQueryClient,
settleQueryNotifications
} from '../../test-support/rpc-recording/hook-mount'
import { describe, expect, it, vi } from 'vitest'
import { FakeSession } from '../../transport/connection/mobile-endpoint-supervisor-test-fakes'
import {
folderSourceCatalogQuery,
serverFolderSourceCatalogQuery,
selectFolderSourceRepos
} from './folder-source-repos-query'
@@ -64,61 +54,3 @@ describe('folder source repositories', () => {
expect(selectFolderSourceRepos(catalog, 'group-1').map((found) => found.id)).toEqual(['api'])
})
})
describe('folder source catalog reads', () => {
let renderer: ReactTestRenderer | null = null
const queries = documentQueryClient()
afterEach(async () => {
act(() => renderer?.unmount())
renderer = null
await queries.end()
})
it.each([true, false])(
"reads a server folder's catalog on the desktop's one event stream (subscribed: %s)",
async (subscribed) => {
let eventStreams = 0
const desktop = stubRpcClient({
getLastConnectedAt: () => 1,
sendRequest: async (method) => ({
id: '1',
ok: true,
result: method === 'repo.list' ? { repos: [] } : { groups: [GROUP] },
_meta: { runtimeId: 'r' }
}),
subscribe: (method) => {
if (method === 'runtime.clientEvents.subscribe') {
eventStreams += 1
}
return () => {}
}
})
const server = scopeRpcClientToExecutionHost(desktop, 'runtime:env-1')
function Harness(): null {
useHostQuery(
folderSourceCatalogQuery,
{ hostId: 'host-1', client: desktop },
{ exec: 'local' },
{},
{
subscribed: true
}
)
useHostQuery(
serverFolderSourceCatalogQuery,
{ hostId: 'host-1', client: server },
{ exec: 'runtime:env-1' },
{},
{ subscribed }
)
return null
}
await act(async () => {
renderer = create(queries.wrap(createElement(Harness)))
})
await settleQueryNotifications()
expect(eventStreams).toBe(1)
}
)
})
@@ -1,11 +1,7 @@
import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rpc/rpc-operation'
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import { sessionWorktreeRecordSchema } from '../../worktree/session-worktree-record-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../terminal/terminal-reply-schema'
import '../../terminal/session/mobile-session-terminal-reply-schema'
import '../../session/tabs/mobile-session-tab-write-reply-schema'
import '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../terminal/quick-commands/mobile-quick-command-operations'
// Preserve host refusal text for optimistic rollback; the reply's record carries the host's merged notes.
@@ -1,110 +0,0 @@
import { createElement } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { TerminalQuickCommand } from '../../../../src/shared/terminal/quick-commands/terminal-quick-command-types'
import { QuickCommandRow } from './QuickCommandRow'
const clipboard = vi.hoisted(() => ({ setStringAsync: vi.fn(() => Promise.resolve(true)) }))
const haptics = vi.hoisted(() => ({ notificationAsync: vi.fn(() => Promise.resolve()) }))
vi.mock('react-native', () => ({
Platform: { OS: 'ios' },
Pressable: 'Pressable',
StyleSheet: { create: <T>(styles: T) => styles, hairlineWidth: 1 },
Text: 'Text',
View: 'View'
}))
vi.mock('lucide-react-native', () => ({
Check: 'Check',
Copy: 'Copy',
Pencil: 'Pencil',
Play: 'Play',
Trash2: 'Trash2'
}))
vi.mock('expo-clipboard', () => clipboard)
vi.mock('expo-haptics', () => ({
...haptics,
performAndroidHapticsAsync: vi.fn(() => Promise.resolve()),
AndroidHaptics: { Reject: 'reject' },
NotificationFeedbackType: { Error: 'error', Success: 'success' }
}))
vi.mock('../../components/MobileAgentIcon', () => ({ MobileAgentIcon: 'MobileAgentIcon' }))
const COMMAND: TerminalQuickCommand = {
id: 'qc-1',
label: 'Run tests',
command: 'run the tests',
appendEnter: true
}
// Require visible error feedback and haptics when clipboard writes reject; a failed write must never show Copied.
describe('the quick-command row when the pasteboard refuses the text', () => {
let renderer: ReactTestRenderer | null = null
beforeEach(() => {
clipboard.setStringAsync.mockReset()
haptics.notificationAsync.mockReset()
haptics.notificationAsync.mockImplementation(() => Promise.resolve())
})
afterEach(() => {
act(() => renderer?.unmount())
renderer = null
})
// Find by every copy-state label so feedback transitions cannot make the control disappear from assertions.
const COPY_LABELS = new Set([
`Copy ${COMMAND.label}`,
'Copied',
"Couldn't copy",
'Nothing to copy'
])
function copyButton() {
const button = renderer!.root
.findAll((node) => node.props.accessibilityRole === 'button')
.find((node) => COPY_LABELS.has(String(node.props.accessibilityLabel)))
if (button === undefined) {
throw new Error('the row has no copy button')
}
return button
}
function rowProps() {
return {
command: COMMAND,
first: true,
onLaunch: vi.fn(),
onEdit: vi.fn(),
onDelete: vi.fn(),
disabled: false
}
}
it('emits nothing at all when the row is gone before the refusal arrives', async () => {
// Unmount before rejection; feedback without a surviving row would buzz with no explanation.
let refuse: ((error: Error) => void) | undefined
clipboard.setStringAsync.mockImplementation(
() =>
new Promise((_resolve, reject) => {
refuse = reject
})
)
await act(async () => {
renderer = create(createElement(QuickCommandRow, rowProps()))
})
await act(async () => {
copyButton().props.onPress()
})
act(() => renderer?.unmount())
renderer = null
await act(async () => {
refuse?.(new Error('pasteboard refused'))
})
expect(haptics.notificationAsync).not.toHaveBeenCalled()
})
})
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import '../terminal-reply-schema'
import { terminalQuickCommandsSchema } from './mobile-quick-command-reply-schema'
import '../../session/agent-launch/mobile-agent-detection-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../session/mobile-session-terminal-reply-schema'
import '../../worktree/session-worktree-record-reply-schema'
import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../../files/workspace-file-paths-reply-schema'
export const quickCommandsReader = rpcResultVariant(
'terminal-quick-commands',
@@ -26,8 +19,6 @@ export const quickCommandsRead = bindDeferredRpcOperation(
})
)
import '../../session/tabs/mobile-session-tab-write-reply-schema'
export const quickCommandsWrite = bindDeferredRpcOperation(
defineRpcOperation({
name: 'settings.quick-commands-write',
@@ -1,5 +1,4 @@
import * as z from 'zod'
import '../../../../src/shared/zod-salvage'
// Preserve null for unreadable canonical command lists so load/save cannot erase host commands with an invented empty list.
export const terminalQuickCommandsSchema = z
@@ -2,13 +2,7 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../../transport/rp
import { rpcResultVariant } from '../../transport/rpc/rpc-operation-result-reader'
import { terminalComposerDraftSchema, terminalSendAcceptedSchema } from '../terminal-reply-schema'
import { sessionTerminalInventorySchema } from './mobile-session-terminal-reply-schema'
import '../../session/agent-launch/mobile-agent-detection-reply-schema'
import '../../files/session-documents/mobile-markdown-tab-reply-schema'
import { sessionWriteUnreadReplySchema } from '../../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../../worktree/session-worktree-record-reply-schema'
import '../../session/native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../quick-commands/mobile-quick-command-reply-schema'
import '../../files/workspace-file-paths-reply-schema'
export const nativeChatTerminalDraftRead = bindDeferredRpcOperation(
defineRpcOperation({
@@ -31,7 +25,6 @@ export const sessionTerminalListRead = bindDeferredRpcOperation(
})
)
import '../../session/tabs/mobile-session-tab-write-reply-schema'
import '../quick-commands/mobile-quick-command-operations'
// Keep chat writes distinct from query/accessory responders: losing a reply here means unknown delivery and forbids automatic retry.
@@ -1,5 +1,4 @@
import * as z from 'zod'
import '../../../../src/shared/zod-salvage'
// Leave unread replies opaque; structured creates/probes require raw-envelope uncertainty checks at their callers.
export const sessionLaunchUnreadReplySchema = z.unknown()
@@ -56,7 +56,6 @@ function brotliHost() {
totalBytes: assets.reduce((total, entry) => total + entry.byteLength, 0),
assets
}
const methods: string[] = []
const answer = (method: string, params: Record<string, unknown>): unknown => {
if (method === 'mobileWeb.bundle.manifest') {
return { manifest, chunkBytes: RANGE_BYTES, rangeBytes: RANGE_BYTES }
@@ -79,7 +78,6 @@ function brotliHost() {
}
const client: RpcClient = {
sendRequest: vi.fn(async (method: string, params?: unknown): Promise<RpcResponse> => {
methods.push(method)
const fields: Record<string, unknown> = Object(params)
return { id: 'rpc-1', ok: true, result: answer(method, fields), _meta: { runtimeId: 'r' } }
}),
@@ -92,7 +90,7 @@ function brotliHost() {
notifyForeground: vi.fn(),
close: vi.fn()
}
return { client, methods }
return { client }
}
describe('fetchMobileWebBundle from a host that ships brotli copies', () => {
@@ -107,10 +105,6 @@ describe('fetchMobileWebBundle from a host that ships brotli copies', () => {
expect(new TextDecoder().decode(fetched.assets.get('assets/script.js'))).toBe(SCRIPT)
expect(new TextDecoder().decode(fetched.assets.get('index.html'))).toBe(MARK)
expect(host.methods.filter((method) => method === 'mobileWeb.bundle.brotliRange')).toHaveLength(
3
)
expect(host.methods.filter((method) => method === 'mobileWeb.bundle.range')).toHaveLength(1)
// The 46-byte copy plus the 12-byte mark, not the 1,332 bytes they inflate to.
expect(progress.at(-1)).toMatchObject({ receivedBytes: 58, totalBytes: 58 })
})
@@ -2,13 +2,6 @@ import { bindDeferredRpcOperation, defineRpcOperation } from '../transport/rpc/r
import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader'
import '../terminal/terminal-reply-schema'
import { sessionWorktreeRecordSchema } from './session-worktree-record-reply-schema'
import '../session/agent-launch/mobile-agent-detection-reply-schema'
import '../files/session-documents/mobile-markdown-tab-reply-schema'
import '../transport/rpc/rpc-uninterpreted-reply-schemas'
import '../terminal/session/mobile-session-terminal-reply-schema'
import '../session/native-chat/composer/mobile-native-chat-skill-reply-schema'
import '../terminal/quick-commands/mobile-quick-command-reply-schema'
import '../files/workspace-file-paths-reply-schema'
// Read the whole worktree for notes and live title; unlike mutation readers, absent records need no error or wrong-host fallback.
export const sessionWorktreeRecordRead = bindDeferredRpcOperation(
@@ -34,14 +34,18 @@ const mocks: {
export { mocks }
vi.mock('node:fs/promises', () => ({ mkdir: mocks.mkdir }))
vi.mock('node:fs/promises', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
mkdir: mocks.mkdir
}))
vi.mock('../orcad/orcad-data-root-locality', () => ({ orcadDataRootIsOnLocalDisk: () => true }))
vi.mock('../git/worktrees/catalog/worktree-scan-cache', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
listWorktreeGraph: mocks.listWorktreeGraph
}))
vi.mock('../git/worktrees/creation/worktree-create-preparation', () => ({
vi.mock('../git/worktrees/creation/worktree-create-preparation', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
prepareWorktreeCreateCheckout: mocks.prepareCheckout,
finalizePreparedWorktree: mocks.finalize,
discardPreparedWorktree: mocks.discard,
@@ -90,10 +94,14 @@ export const store = { getSettings: () => ({}) } as unknown as Store
beforeEach(() => {
mocks.mkdir.mockReset().mockResolvedValue(undefined)
mocks.listWorktreeGraph.mockReset().mockResolvedValue([])
mocks.prepareCheckout.mockReset().mockResolvedValue(undefined)
mocks.prepareCheckout
.mockReset()
.mockImplementation(async (repo, path, _base, reason, _options, _barrier, operation) => {
operation?.setDiscard((options) => mocks.discard(repo, path, options, reason, null))
})
mocks.refreshTip.mockReset().mockResolvedValue(undefined)
mocks.finalize.mockReset().mockResolvedValue({})
mocks.discard.mockReset().mockResolvedValue(undefined)
mocks.discard.mockReset().mockResolvedValue('removed')
mocks.unlock.mockReset().mockResolvedValue(undefined)
mocks.getWorktreeOptions.mockReset().mockReturnValue({})
mocks.measureDivergence.mockReset().mockResolvedValue('within')
@@ -1,89 +0,0 @@
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
)
}
})
@@ -71,27 +71,6 @@ it('reads only cached support and rejects a retired acquisition or changed accou
}
})
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)
@@ -560,7 +560,7 @@ describe('prepared worktree creation with real Git', () => {
controller.abort()
await expect(
discardPreparedWorktree(repoPath, preparedPath, { signal: controller.signal }, lockReason)
).resolves.toBeUndefined()
).resolves.toBe('removed')
expect(await listWorktrees(repoPath, { includeCreatePreparations: true })).toHaveLength(1)
})
@@ -621,3 +621,65 @@ describe('prepared worktree creation with real Git', () => {
)
})
})
it.each(['replacement', 'permission'])(
'preserves the requested path when rollback loses %s authority',
async (kind) => {
const { repoPath, root } = await createRepo()
const prepared = join(root, 'prepared-rollback-authority')
const target = join(root, 'rollback-target')
const preserved = join(root, 'preserved-original')
const reason = createWorktreePreparationLockReason('rollback-authority')
await prepareWorktreeCreateCheckout(repoPath, prepared, 'main', reason)
const originalLock = git(prepared, ['rev-parse', '--git-path', 'locked'])
const failure = new Error('move rewrote pointers but rejected')
const run = gitRunner.gitExecFileAsync
let allowed = true
let replaced = false
vi.spyOn(gitRunner, 'gitExecFileAsync').mockImplementation(async (args, options) => {
if (args.includes('move')) {
await run(args, options)
if (kind === 'permission') {
allowed = false
}
throw failure
}
if (
kind === 'replacement' &&
args[0] === 'symbolic-ref' &&
options.cwd === target &&
!replaced
) {
replaced = true
git(repoPath, ['worktree', 'move', '-f', '-f', target, preserved])
git(repoPath, ['worktree', 'add', '--detach', target, 'HEAD'])
git(repoPath, ['worktree', 'lock', '--reason', reason, target])
await writeFile(join(target, 'user.txt'), 'preserve replacement\n')
}
return run(args, options)
})
try {
await expect(
finalizePreparedWorktree(
repoPath,
prepared,
target,
'rollback-authority',
'main',
false,
{ canStart: () => allowed },
reason
)
).rejects.toBe(failure)
expect(await readFile(join(target, 'version.txt'), 'utf8')).toBe('one\n')
if (kind === 'replacement') {
expect(replaced).toBe(true)
expect(await readFile(join(target, 'user.txt'), 'utf8')).toBe('preserve replacement\n')
expect(await readFile(join(preserved, 'version.txt'), 'utf8')).toBe('one\n')
}
expect(await readFile(originalLock, 'utf8')).toBe(`${reason}\n`)
} finally {
vi.restoreAllMocks()
}
}
)
@@ -1,3 +1,5 @@
import { runStandalonePreparation } from './worktree-preparation-standalone'
import { performPreparedWorktreeFinalization } from './worktree-preparation-finalization-work'
import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args'
import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args'
import { resolveWorktreeAddBaseRef } from '../../../../shared/worktree/base-ref'
@@ -11,28 +13,20 @@ import {
resolveWorktreeAddTimeoutMs,
WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS
} from '../worktree-operation-options'
import {
configurePushAutoSetupRemote,
persistWorktreeCreationBase,
resolveWorktreeAddBaseContext,
trackSameNameRemoteBase
} from './worktree-add'
import { bumpWorktreeScanGeneration as notifyPreparedWorktreeMutation } from '../catalog/worktree-scan-cache'
import { gitCleanupOptions, removeFailedFinalization } from './worktree-preparation-discard'
import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe'
import {
runStandalonePreparation,
type WorktreePreparationOperation
} from './worktree-preparation-operation'
gitCleanupOptions,
removeFailedFinalization,
reconcilePreparationLocation,
discardPreparedWorktree as discardOwnedPreparation
} from './worktree-preparation-discard'
import { hasWorktreeBaseCommitRef } from './worktree-base-ref-probe'
import { WorktreePreparationOperation } from './worktree-preparation-operation'
import { gitExecFileAsync } from '../../command-runner/git-exec-file'
import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation'
import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing'
import {
unlockWorktreePreparation,
unlockWorktreePreparationAtPath,
verifyWorktreePreparationLock,
verifyWorktreePreparationLockAtPath,
WorktreePreparationLockOwnershipError
verifyWorktreePreparationLockAtPath
} from './worktree-preparation-lock'
import { addLockedWorktreePreparation } from './worktree-preparation-add'
@@ -139,6 +133,12 @@ export type FinalizedPreparedWorktree = AddWorktreeResult & {
preparedHeadReset: boolean
}
export class PreparedWorktreeFinalizationPendingError extends Error {
constructor(readonly originalError: unknown) {
super('The prepared checkout still has an unverified target writer.', { cause: originalError })
}
}
export async function finalizePreparedWorktree(
repoPath: string,
preparedPath: string,
@@ -147,149 +147,110 @@ export async function finalizePreparedWorktree(
baseBranch: string,
refreshLocalBaseRef = false,
options: AddWorktreeOptions = {},
expectedLockReason: string
expectedLockReason: string,
operation?: WorktreePreparationOperation
): Promise<FinalizedPreparedWorktree> {
const finalizeGitOptions: AddWorktreeOptions = {
...options,
timeout: options.timeout ?? resolveWorktreeAddTimeoutMs()
const owner = operation ?? new WorktreePreparationOperation(options)
let pendingTarget = false
const captured: { lockPath?: string; targetWriter: boolean } = { targetWriter: false }
if (!operation) {
owner.setDiscard((cleanupOptions) =>
discardOwnedPreparation(repoPath, preparedPath, cleanupOptions, expectedLockReason)
)
}
try {
return await runWithGitReadCacheInvalidation(async () => {
const lockPath = await verifyWorktreePreparationLock(
const result = await owner.supervise(options, (ownedOptions) =>
performPreparedWorktreeFinalization(
repoPath,
preparedPath,
worktreePath,
branch,
baseBranch,
refreshLocalBaseRef,
{ ...options, ...ownedOptions },
expectedLockReason,
finalizeGitOptions
owner,
captured
)
const verifyOwnership = (): Promise<void> =>
verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, finalizeGitOptions.signal)
const [targetResult, preparedResult] = await Promise.allSettled([
(async () => {
const baseContext = await resolveWorktreeAddBaseContext(
repoPath,
baseBranch,
refreshLocalBaseRef,
finalizeGitOptions,
branch
)
const targetHead =
baseContext.effectiveBaseOid ??
(
await gitExecFileAsync(
['rev-parse', '--verify', `${baseContext.effectiveBase}^{commit}`],
gitExecOptions(repoPath, finalizeGitOptions)
)
).stdout.trim()
return { baseContext, targetHead }
})(),
gitExecFileAsync(
['rev-parse', '--verify', 'HEAD'],
gitExecOptions(preparedPath, finalizeGitOptions)
)
])
// Settle both reads before failure cleanup can remove the prepared checkout.
if (targetResult.status === 'rejected') {
throw targetResult.reason
}
const { baseContext, targetHead } = targetResult.value
if (preparedResult.status === 'rejected') {
await baseContext.pendingLocalBaseRefRefresh
throw preparedResult.reason
}
const preparedHeadReset = preparedResult.value.stdout.trim() !== targetHead
if (preparedHeadReset) {
await verifyOwnership()
await gitExecFileAsync(
[
...(await checkoutWorkersGitArgs(preparedPath, finalizeGitOptions)),
...windowsLongPathGitArgs(preparedPath),
'reset',
'--hard',
targetHead
],
gitExecOptions(preparedPath, finalizeGitOptions)
)
}
let moved = false
try {
try {
await verifyOwnership()
// Git >= 2.25 needs two force flags to move a locked preparation without losing its lock reason.
await gitExecFileAsync(
[
...windowsLongPathGitArgs(repoPath),
'worktree',
'move',
'-f',
'-f',
preparedPath,
worktreePath
],
gitExecOptions(repoPath, finalizeGitOptions)
)
moved = true
} finally {
// The move rewrites both `.git` markers, and a failure can have rewritten one.
invalidateWslLinkedWorktreeGitRouting(preparedPath)
invalidateWslLinkedWorktreeGitRouting(worktreePath)
)
await owner.physicalSettlement()
owner.finishFinalization('disposed')
return result
} catch (error) {
const settled = await owner.waitForPhysicalSettlement()
if (captured.lockPath) {
owner.setDiscard(async (cleanupOptions) => {
if (!captured.lockPath) {
return 'revoked'
}
await verifyOwnership()
await gitExecFileAsync(
[
...windowsLongPathGitArgs(worktreePath),
'checkout',
'--no-track',
'-b',
branch,
targetHead
],
gitExecOptions(worktreePath, finalizeGitOptions)
)
await verifyOwnership()
await persistWorktreeCreationBase(
const location = await reconcilePreparationLocation(
captured.lockPath,
preparedPath,
worktreePath,
branch,
baseContext.effectiveBase,
finalizeGitOptions
)
await trackSameNameRemoteBase(
worktreePath,
branch,
baseBranch,
baseContext.effectiveBase,
finalizeGitOptions
)
await configurePushAutoSetupRemote(worktreePath, finalizeGitOptions)
await unlockWorktreePreparationAtPath(
lockPath,
expectedLockReason,
finalizeGitOptions.signal
cleanupOptions
)
} catch (error) {
if (!(error instanceof WorktreePreparationLockOwnershipError)) {
await removeFailedFinalization(
if (location === 'hidden') {
return discardOwnedPreparation(
repoPath,
moved ? worktreePath : preparedPath,
branch,
moved,
finalizeGitOptions,
expectedLockReason
preparedPath,
cleanupOptions,
expectedLockReason,
captured.lockPath
)
}
await baseContext.pendingLocalBaseRefRefresh
throw error
return location === 'target' || location === 'unknown' ? 'revoked' : location
})
}
if (settled && captured.lockPath) {
const location = await reconcilePreparationLocation(
captured.lockPath,
preparedPath,
worktreePath,
expectedLockReason,
options
)
if (location === 'target') {
let eligible = true
const rollback = owner.supervise(
{
...options,
signal: undefined,
canStart: () => eligible && options.canStart?.() !== false
},
(rollbackOptions) =>
removeFailedFinalization(
repoPath,
worktreePath,
branch,
true,
rollbackOptions,
expectedLockReason,
captured.lockPath
),
true
)
void rollback.catch(() => {})
pendingTarget = !(await owner.waitForPhysicalSettlement(() => {
eligible = false
}))
eligible = false
if (!pendingTarget && (await rollback.catch(() => false))) {
owner.finishFinalization('disposed')
}
}
// Advisory refresh may settle after finalization; it does not determine checkout contents.
const localBaseRefRefresh = await baseContext.pendingLocalBaseRefRefresh
return {
preparedHeadReset,
...(localBaseRefRefresh ? { localBaseRefRefresh } : {}),
...(baseContext.localBaseRefUpdateSuggestion
? { localBaseRefUpdateSuggestion: baseContext.localBaseRefUpdateSuggestion }
: {})
}
})
} else {
pendingTarget = captured.targetWriter
}
owner.finishFinalization(!settled || pendingTarget ? 'pending' : 'failed')
if (!operation) {
await owner.discard()
}
if (pendingTarget && operation) {
throw new PreparedWorktreeFinalizationPendingError(error)
}
throw error
} finally {
notifyPreparedWorktreeMutation(repoPath)
owner.finishFinalization()
}
}
@@ -1,3 +1,4 @@
import { runStandalonePreparation } from './worktree-preparation-standalone'
import { lstat } from 'node:fs/promises'
import { isUnsupportedWorktreeAddLockReasonError } from '../../../../shared/git/worktrees/git-worktree-command-capabilities'
import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path'
@@ -11,11 +12,11 @@ import {
WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
type GitWorktreeExecOptions
} from '../worktree-operation-options'
import type { WorktreePreparationOperation } from './worktree-preparation-operation'
import {
runStandalonePreparation,
type WorktreePreparationOperation
} from './worktree-preparation-operation'
import { discardPreparedWorktree } from './worktree-preparation-discard'
discardPreparedWorktree,
type PreparationRemovalOutcome
} from './worktree-preparation-discard'
import {
lockWorktreePreparation,
verifyWorktreePreparationLock,
@@ -39,6 +40,14 @@ async function isAbsent(worktreePath: string, options: GitWorktreeExecOptions):
}
}
/** The owner has fenced its raw work and no add was issued for this unique path. */
export async function discardUnmaterializedPreparation(
path: string,
options: GitWorktreeExecOptions
): Promise<PreparationRemovalOutcome> {
return (await isAbsent(path, options)) ? 'removed' : 'revoked'
}
export async function addLockedWorktreePreparation(
repoPath: string,
worktreePath: string,
@@ -61,32 +70,50 @@ export async function addLockedWorktreePreparation(
)
)
}
const add = async (lockArgs: string[]): Promise<void> => {
options.signal?.throwIfAborted()
try {
await gitExecFileAsync(
[
...windowsLongPathGitArgs(repoPath),
'worktree',
'add',
'--detach',
'--no-checkout',
...lockArgs,
worktreePath,
baseRef
],
gitExecOptions(repoPath, options)
)
} finally {
invalidateWslLinkedWorktreeGitRouting(worktreePath)
}
}
return withLocalGitCapabilityCacheForExecution(
{ cwd: repoPath, wslDistro: options.wslDistro, signal: options.signal },
async (capabilities) => {
options.signal?.throwIfAborted()
const initiallyAbsent = await isAbsent(worktreePath, options)
options.signal?.throwIfAborted()
let issued = false
const add = async (lockArgs: string[]): Promise<void> => {
options.signal?.throwIfAborted()
try {
await gitExecFileAsync(
[
...windowsLongPathGitArgs(repoPath),
'worktree',
'add',
'--detach',
'--no-checkout',
...lockArgs,
worktreePath,
baseRef
],
{
...gitExecOptions(repoPath, options),
observeChildTermination: (terminated, writes) => {
if (writes) {
issued = true
operation.setDiscard((cleanupOptions) =>
discardPreparedWorktree(
repoPath,
worktreePath,
cleanupOptions,
lockReason,
initiallyAbsent ? null : undefined
)
)
}
options.observeChildTermination?.(terminated, writes)
}
}
)
} finally {
invalidateWslLinkedWorktreeGitRouting(worktreePath)
}
}
return capabilities.runWithFallback(
'worktree-add-lock-reason',
async () => {
@@ -96,10 +123,13 @@ export async function addLockedWorktreePreparation(
added = true
const lockPath = await verifyWorktreePreparationLock(worktreePath, lockReason, options)
operation.setDiscard((cleanupOptions) =>
discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason)
discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason, lockPath)
)
return lockPath
} catch (error) {
if (!issued) {
throw error
}
operation.setDiscard()
// A canceled add can leave its marker; a pre-existing checkout is never ours to remove.
if (
@@ -108,7 +138,13 @@ export async function addLockedWorktreePreparation(
!(error instanceof WorktreePreparationLockOwnershipError)
) {
operation.setDiscard((cleanupOptions) =>
discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason)
discardPreparedWorktree(
repoPath,
worktreePath,
cleanupOptions,
lockReason,
initiallyAbsent ? null : undefined
)
)
}
throw error
@@ -126,10 +162,13 @@ export async function addLockedWorktreePreparation(
operation
)
operation.setDiscard((cleanupOptions) =>
discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason)
discardPreparedWorktree(repoPath, worktreePath, cleanupOptions, lockReason, lockPath)
)
return lockPath
} catch (error) {
if (!issued) {
throw error
}
operation.setDiscard()
if (
added &&
@@ -56,7 +56,7 @@ it('removes only the owned registration after external deletion of its checkout'
['rev-parse', '--git-path', 'locked', '--git-common-dir'],
['worktree', 'remove', '--force', '--force', prepared]
])
expect(spy.mock.calls[1]?.[1]).toEqual({
expect(spy.mock.calls[1]?.[1]).toMatchObject({
cwd: repo,
timeout: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS
})
@@ -168,3 +168,42 @@ it.runIf(process.platform !== 'win32')('does not follow a symlink ownership mark
expect(spy.mock.calls.some(([args]) => args.includes('remove'))).toBe(false)
expect(await readFile(externalLock, 'utf8')).toBe(`${reason}\n`)
})
it('preserves a replacement even when its ownership text was copied', async () => {
const { repo, prepared, lock, reason } = await fixture()
const replacement = join(dirname(repo), 'replacement')
await runner.gitExecFileAsync(['worktree', 'add', '--detach', replacement, 'HEAD'], { cwd: repo })
await runner.gitExecFileAsync(['worktree', 'lock', '--reason', reason, replacement], {
cwd: repo
})
const pointer = await readFile(join(replacement, '.git'), 'utf8')
await writeFile(join(prepared, '.git'), pointer)
await writeFile(join(prepared, 'user.txt'), 'preserve replacement\n')
await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason, lock)).rejects.toThrow(
'lock owner changed'
)
expect(await readFile(join(prepared, 'user.txt'), 'utf8')).toBe('preserve replacement\n')
expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`)
})
it('preserves a different missing-checkout registration with copied ownership text', async () => {
const { repo, prepared, lock, reason } = await fixture()
const preserved = join(dirname(repo), 'preserved-original')
await runner.gitExecFileAsync(['worktree', 'move', '-f', '-f', prepared, preserved], {
cwd: repo
})
await runner.gitExecFileAsync(
['worktree', 'add', '--detach', '--no-checkout', prepared, 'HEAD'],
{ cwd: repo }
)
await runner.gitExecFileAsync(['worktree', 'lock', '--reason', reason, prepared], { cwd: repo })
const replacementLock = (
await runner.gitExecFileAsync(['rev-parse', '--git-path', 'locked'], { cwd: prepared })
).stdout.trim()
await rm(prepared, { recursive: true })
await expect(performDiscardPreparedWorktree(repo, prepared, {}, reason, lock)).rejects.toThrow(
'lock owner changed'
)
expect(await readFile(replacementLock, 'utf8')).toBe(`${reason}\n`)
expect(await readFile(lock, 'utf8')).toBe(`${reason}\n`)
})
@@ -1,9 +1,14 @@
import { bumpWorktreeScanGeneration } from '../catalog/worktree-scan-cache'
import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation'
import { lstat } from 'node:fs/promises'
import { join } from 'node:path'
import { lstat, readFile, realpath } from 'node:fs/promises'
import { dirname, join } from 'node:path'
import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason'
import { resolveWorktreeHostPath } from '../../../../shared/git/metadata/git-metadata-path'
import { parseGitdirMarkerPayload } from '../../../../shared/git/metadata/gitdir-marker-payload'
import { canonicalWorktreePath } from '../catalog/worktree-path-comparison'
import {
resolveGitMetadataPath,
resolveWorktreeHostPath
} from '../../../../shared/git/metadata/git-metadata-path'
import { findLinkedWorktreeGitDirectory } from '../../../../shared/git/worktrees/git-worktree-admin'
import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args'
import { toHostFilesystemPath } from '../../../filesystem/host-tree-removal'
@@ -16,6 +21,7 @@ import {
type GitWorktreeExecOptions
} from '../worktree-operation-options'
import {
verifyOriginalPreparationDirectory,
verifyWorktreePreparationLock,
verifyWorktreePreparationLockAtPath,
WorktreePreparationLockOwnershipError
@@ -34,14 +40,23 @@ async function verifyDiscardPreparationOwner(
repoPath: string,
worktreePath: string,
expectedLockReason: string,
options: GitExecOptionsForWorktree
): Promise<void> {
options: GitExecOptionsForWorktree,
originalLockPath?: string | null
): Promise<string | null> {
try {
await verifyWorktreePreparationLock(worktreePath, expectedLockReason, options)
} catch (error) {
if (error instanceof WorktreePreparationLockOwnershipError) {
throw error
const gitDir = dirname(
await verifyWorktreePreparationLock(worktreePath, expectedLockReason, options)
)
if (originalLockPath) {
await verifyOriginalPreparationDirectory(gitDir, originalLockPath)
}
await verifyWorktreePreparationLockAtPath(
join(gitDir, 'locked'),
expectedLockReason,
options.signal
)
return gitDir
} catch (error) {
const hostPath = resolveWorktreeHostPath(worktreePath, options)
const hostRepo = resolveWorktreeHostPath(repoPath, options)
if (!hostPath || !hostRepo) {
@@ -65,8 +80,17 @@ async function verifyDiscardPreparationOwner(
}
const gitDir = await findLinkedWorktreeGitDirectory(hostRepo, hostPath, { ...options, signal })
if (!gitDir) {
if (
originalLockPath === null ||
(originalLockPath && (await pathAbsent(dirname(originalLockPath))))
) {
return null
}
throw new WorktreePreparationLockOwnershipError(error)
}
if (originalLockPath) {
await verifyOriginalPreparationDirectory(gitDir, originalLockPath)
}
const lockPath = toHostFilesystemPath(join(gitDir, 'locked'))
const marker = await waitForPromiseWithSignal(lstat(lockPath), signal).catch(
(failure: unknown) => {
@@ -80,6 +104,87 @@ async function verifyDiscardPreparationOwner(
verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, signal),
signal
)
return gitDir
}
}
export type PreparationRemovalOutcome = 'removed' | 'skipped' | 'ownership-lost' | 'revoked'
async function pathAbsent(path: string, options: GitWorktreeExecOptions = {}): Promise<boolean> {
const hostPath = resolveWorktreeHostPath(path, options)
if (!hostPath) {
throw new Error('Cannot resolve the prepared checkout path.')
}
return lstat(toHostFilesystemPath(hostPath)).then(
() => false,
(error: unknown) => {
if (getErrorCode(error) === 'ENOENT') {
return true
}
throw error
}
)
}
export type PreparationLocation = 'hidden' | 'target' | 'removed' | 'ownership-lost' | 'unknown'
/** Both pointers and the original marker must agree before failed finalization can remove a path. */
export async function reconcilePreparationLocation(
lockPath: string,
hiddenPath: string,
targetPath: string,
lockReason: string,
options: GitWorktreeExecOptions
): Promise<PreparationLocation> {
const gitDir = dirname(lockPath)
const signal = AbortSignal.timeout(options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS)
const read = <T>(work: Promise<T>): Promise<T> => waitForPromiseWithSignal(work, signal)
try {
const [hiddenAbsent, targetAbsent, adminAbsent] = await read(
Promise.all([
pathAbsent(hiddenPath, options),
pathAbsent(targetPath, options),
pathAbsent(gitDir)
])
)
if (hiddenAbsent && targetAbsent && adminAbsent) {
return 'removed'
}
if (adminAbsent) {
return 'unknown'
}
await read(verifyWorktreePreparationLockAtPath(lockPath, lockReason, signal))
const backlink = await read(readFile(join(gitDir, 'gitdir'), 'utf8'))
const gitFile = resolveGitMetadataPath(gitDir, backlink, options)
if (!gitFile) {
return 'unknown'
}
const path = dirname(gitFile)
const key = async (value: string): Promise<string> =>
canonicalWorktreePath(await read(realpath(toHostFilesystemPath(value))).catch(() => value))
const hidden = resolveWorktreeHostPath(hiddenPath, options)
const target = resolveWorktreeHostPath(targetPath, options)
const location =
hidden && (await key(path)) === (await key(hidden))
? 'hidden'
: target && (await key(path)) === (await key(target))
? 'target'
: undefined
if (!location || (await key(gitFile)) !== (await key(join(path, '.git')))) {
return 'unknown'
}
const pointer = await read(readFile(toHostFilesystemPath(gitFile), 'utf8'))
const marker = parseGitdirMarkerPayload(pointer)
const pointedAdmin = marker && resolveGitMetadataPath(path, marker, options)
if (!pointedAdmin || (await key(pointedAdmin)) !== (await key(gitDir))) {
return 'unknown'
}
await read(verifyWorktreePreparationLockAtPath(lockPath, lockReason, signal))
return location
} catch (error) {
return error instanceof WorktreePreparationLockOwnershipError && error.replaced
? 'ownership-lost'
: 'unknown'
}
}
@@ -87,23 +192,36 @@ export async function performDiscardPreparedWorktree(
repoPath: string,
worktreePath: string,
options: GitWorktreeExecOptions,
expectedLockReason?: string
): Promise<void> {
expectedLockReason?: string,
originalLockPath?: string | null
): Promise<PreparationRemovalOutcome> {
const writers: Promise<void>[] = []
const cleanupGitOptions = {
...gitCleanupOptions(repoPath, options),
timeout: options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS
timeout: options.timeout ?? WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
observeChildTermination: (terminated: Promise<void>, writes: boolean) => {
options.observeChildTermination?.(terminated, writes)
if (writes) {
writers.push(terminated)
}
}
}
try {
let gitDir: string | null = null
if (expectedLockReason !== undefined) {
await verifyDiscardPreparationOwner(
gitDir = await verifyDiscardPreparationOwner(
repoPath,
worktreePath,
expectedLockReason,
cleanupGitOptions
cleanupGitOptions,
originalLockPath
)
if (gitDir === null) {
return 'removed'
}
}
if (cleanupGitOptions.canStart?.() === false) {
return
return 'skipped'
}
// Double force requires a freshly verified ownership marker.
await gitExecFileAsync(
@@ -117,6 +235,11 @@ export async function performDiscardPreparedWorktree(
],
cleanupGitOptions
)
await Promise.allSettled(writers)
if (!(await pathAbsent(worktreePath, options)) || (gitDir && !(await pathAbsent(gitDir)))) {
throw new Error('The prepared checkout or its registration remains after removal.')
}
return 'removed'
} finally {
invalidateWslLinkedWorktreeGitRouting(worktreePath)
}
@@ -128,8 +251,9 @@ export async function removeFailedFinalization(
branch: string,
moved: boolean,
options: GitWorktreeExecOptions,
expectedLockReason?: string
): Promise<void> {
expectedLockReason?: string,
originalLockPath?: string
): Promise<boolean> {
let branchAttached = false
if (moved) {
try {
@@ -146,13 +270,14 @@ export async function removeFailedFinalization(
repoPath,
cleanupPath,
options,
expectedLockReason
expectedLockReason,
originalLockPath
).then(
() => true,
(outcome) => outcome === 'removed',
() => false
)
if (!removed) {
return
return false
}
if (branchAttached) {
await gitExecFileAsync(
@@ -160,17 +285,25 @@ export async function removeFailedFinalization(
gitCleanupOptions(repoPath, options)
).catch(() => {})
}
return true
}
export async function discardPreparedWorktree(
repoPath: string,
worktreePath: string,
options: GitWorktreeExecOptions = {},
expectedLockReason?: string
): Promise<void> {
expectedLockReason?: string,
originalLockPath?: string | null
): Promise<PreparationRemovalOutcome> {
try {
await runWithGitReadCacheInvalidation(() =>
performDiscardPreparedWorktree(repoPath, worktreePath, options, expectedLockReason)
return await runWithGitReadCacheInvalidation(() =>
performDiscardPreparedWorktree(
repoPath,
worktreePath,
options,
expectedLockReason,
originalLockPath
)
)
} finally {
bumpWorktreeScanGeneration(repoPath)
@@ -0,0 +1,210 @@
import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters'
import { WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS } from '../worktree-operation-options'
import type { PreparationRemovalOutcome } from './worktree-preparation-discard'
export type SettledPreparationDiscard = {
status: PreparationRemovalOutcome | 'failed'
attempted: boolean
error?: unknown
}
export type PreparationDiscardResult =
| SettledPreparationDiscard
| {
status: 'pending'
settled: Promise<SettledPreparationDiscard>
}
export abstract class WorktreePreparationDisposal {
private discardAttempt?: Promise<void>
private disposalState:
| 'owned'
| 'finalizing'
| 'pending'
| 'active'
| 'parked'
| 'terminal'
| 'released' = 'owned'
private attempts = 0
private wake?: object
private disposalOwner?: {
current: () => boolean
before: () => Promise<boolean>
schedule: (work: () => Promise<void>) => Promise<void>
disposed: () => void
}
abstract physicalSettlement(): Promise<void>
async waitForPhysicalSettlement(onAbandon?: () => void): Promise<boolean> {
return sharedPromiseSettlementWaiters(this.physicalSettlement())
.wait({
timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
onAbandon
})
.then(
() => true,
() => false
)
}
protected abstract retire(): Promise<void>
protected abstract physicalDiscard(
eligible: () => boolean,
before: () => Promise<boolean>,
leaseRetirement: AbortSignal
): Promise<SettledPreparationDiscard>
protected abstract complete(): void
protected beginFinalization(rollback: boolean): void {
if (
!this.current() ||
(this.disposalState !== 'owned' && !(rollback && this.disposalState === 'finalizing'))
) {
throw new Error('The prepared checkout is no longer available for finalization.')
}
this.disposalState = 'finalizing'
}
finishFinalization(outcome: 'disposed' | 'pending' | 'failed' = 'failed'): void {
if (outcome === 'disposed') {
this.disposalOwner?.disposed()
this.release()
} else if (this.disposalState === 'finalizing') {
if (outcome === 'pending') {
this.acceptDiscard({
status: 'pending',
settled: this.physicalSettlement().then(() => ({ status: 'skipped', attempted: false }))
})
} else {
this.disposalState = 'pending'
}
}
}
setDisposalOwner(owner: NonNullable<WorktreePreparationDisposal['disposalOwner']>): void {
this.disposalOwner = owner
}
get needsDiscardRetry(): boolean {
return this.disposalState === 'pending'
}
release(): void {
this.disposalState = 'released'
this.wake = undefined
this.complete()
}
protected current(): boolean {
return this.disposalState !== 'released' && this.disposalOwner?.current() !== false
}
discard(): Promise<void> {
if (
!this.current() ||
this.disposalState === 'finalizing' ||
this.disposalState === 'parked' ||
this.disposalState === 'terminal'
) {
return Promise.resolve()
}
if (this.discardAttempt) {
return this.discardAttempt
}
this.disposalState = 'active'
const run = async (): Promise<void> => this.acceptDiscard(await this.discardOnce())
const attempt = this.disposalOwner ? this.disposalOwner.schedule(run) : run()
this.discardAttempt = attempt
void attempt.then(() => {
if (this.discardAttempt === attempt) {
this.discardAttempt = undefined
}
})
return attempt
}
private acceptDiscard(result: PreparationDiscardResult): void {
if (!this.current()) {
return
}
if (result.status !== 'pending') {
this.finishDiscard(result, false)
return
}
const token = {}
this.wake = token
this.disposalState = 'parked'
void result.settled.then((settled) => {
if (!this.current() || this.disposalState !== 'parked' || this.wake !== token) {
return
}
this.wake = undefined
this.finishDiscard(settled, true)
})
}
private finishDiscard(result: SettledPreparationDiscard, wake: boolean): void {
if (!this.current()) {
return
}
if (result.attempted) {
this.attempts += 1
}
if (result.status === 'removed' || result.status === 'ownership-lost') {
this.disposalOwner?.disposed()
this.release()
return
}
if (result.status === 'revoked' || this.attempts >= 3) {
this.disposalState = 'terminal'
console.warn(
'[worktree-create] prepared checkout remains; automatic cleanup stopped',
result.error
)
return
}
this.disposalState = 'pending'
if (wake) {
void (this.discardAttempt ?? Promise.resolve()).then(() => {
if (this.current() && this.needsDiscardRetry) {
void this.discard()
}
})
}
}
private async discardOnce(): Promise<PreparationDiscardResult> {
const retirement = this.retire()
const retired = await sharedPromiseSettlementWaiters(retirement)
.wait({
timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS
})
.then(
() => true,
() => false
)
if (!retired) {
return {
status: 'pending',
settled: retirement.then(() => ({ status: 'skipped', attempted: false }))
}
}
let eligible = true
const leaseRetirement = new AbortController()
const settled = this.physicalDiscard(
() => eligible && this.current(),
() => this.disposalOwner?.before() ?? Promise.resolve(true),
leaseRetirement.signal
)
const result = await sharedPromiseSettlementWaiters(settled)
.wait({
timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
onAbandon: () => {
eligible = false
leaseRetirement.abort()
}
})
.catch(() => ({ status: 'pending' as const, settled }))
eligible = false
return result
}
}
@@ -0,0 +1,179 @@
import { windowsLongPathGitArgs } from '../../../../shared/windows-long-path-git-args'
import { checkoutWorkersGitArgs } from '../../command-runner/checkout-workers-git-args'
import type { AddWorktreeOptions } from '../worktree-operation-options'
import { gitExecOptions, resolveWorktreeAddTimeoutMs } from '../worktree-operation-options'
import {
configurePushAutoSetupRemote,
persistWorktreeCreationBase,
resolveWorktreeAddBaseContext,
trackSameNameRemoteBase
} from './worktree-add'
import { bumpWorktreeScanGeneration as notifyPreparedWorktreeMutation } from '../catalog/worktree-scan-cache'
import type { WorktreePreparationOperation } from './worktree-preparation-operation'
import { gitExecFileAsync } from '../../command-runner/git-exec-file'
import { runWithGitReadCacheInvalidation } from '../../source-control/git-read-cache-invalidation'
import { invalidateWslLinkedWorktreeGitRouting } from '../../command-runner/wsl-linked-worktree-git-routing'
import {
unlockWorktreePreparationAtPath,
verifyWorktreePreparationLock,
verifyWorktreePreparationLockAtPath
} from './worktree-preparation-lock'
import type { FinalizedPreparedWorktree } from './worktree-create-preparation'
export async function performPreparedWorktreeFinalization(
repoPath: string,
preparedPath: string,
worktreePath: string,
branch: string,
baseBranch: string,
refreshLocalBaseRef = false,
options: AddWorktreeOptions = {},
expectedLockReason: string,
operation: WorktreePreparationOperation,
captured: { lockPath?: string; targetWriter: boolean }
): Promise<FinalizedPreparedWorktree> {
const finalizeGitOptions: AddWorktreeOptions = {
...options,
timeout: options.timeout ?? resolveWorktreeAddTimeoutMs()
}
try {
return await runWithGitReadCacheInvalidation(async () => {
const lockPath = await verifyWorktreePreparationLock(
preparedPath,
expectedLockReason,
finalizeGitOptions
)
captured.lockPath = lockPath
const verifyOwnership = (): Promise<void> =>
verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, finalizeGitOptions.signal)
const [targetResult, preparedResult] = await Promise.allSettled([
(async () => {
const baseContext = await resolveWorktreeAddBaseContext(
repoPath,
baseBranch,
refreshLocalBaseRef,
finalizeGitOptions,
branch
)
if (baseContext.pendingLocalBaseRefRefresh) {
operation.trackWriter(baseContext.pendingLocalBaseRefRefresh)
}
const targetHead =
baseContext.effectiveBaseOid ??
(
await gitExecFileAsync(
['rev-parse', '--verify', `${baseContext.effectiveBase}^{commit}`],
gitExecOptions(repoPath, finalizeGitOptions)
)
).stdout.trim()
return { baseContext, targetHead }
})(),
gitExecFileAsync(
['rev-parse', '--verify', 'HEAD'],
gitExecOptions(preparedPath, finalizeGitOptions)
)
])
// Settle both reads before failure cleanup can remove the prepared checkout.
if (targetResult.status === 'rejected') {
throw targetResult.reason
}
const { baseContext, targetHead } = targetResult.value
if (preparedResult.status === 'rejected') {
await baseContext.pendingLocalBaseRefRefresh
throw preparedResult.reason
}
const preparedHeadReset = preparedResult.value.stdout.trim() !== targetHead
if (preparedHeadReset) {
await verifyOwnership()
await gitExecFileAsync(
[
...(await checkoutWorkersGitArgs(preparedPath, finalizeGitOptions)),
...windowsLongPathGitArgs(preparedPath),
'reset',
'--hard',
targetHead
],
gitExecOptions(preparedPath, finalizeGitOptions)
)
}
try {
try {
await verifyOwnership()
// Git >= 2.25 needs two force flags to move a locked preparation without losing its lock reason.
await gitExecFileAsync(
[
...windowsLongPathGitArgs(repoPath),
'worktree',
'move',
'-f',
'-f',
preparedPath,
worktreePath
],
{
...gitExecOptions(repoPath, finalizeGitOptions),
observeChildTermination: (terminated, writes) => {
if (writes) {
captured.targetWriter = true
}
finalizeGitOptions.observeChildTermination?.(terminated, writes)
}
}
)
} finally {
// The move rewrites both `.git` markers, and a failure can have rewritten one.
invalidateWslLinkedWorktreeGitRouting(preparedPath)
invalidateWslLinkedWorktreeGitRouting(worktreePath)
}
await verifyOwnership()
await gitExecFileAsync(
[
...windowsLongPathGitArgs(worktreePath),
'checkout',
'--no-track',
'-b',
branch,
targetHead
],
gitExecOptions(worktreePath, finalizeGitOptions)
)
await verifyOwnership()
await persistWorktreeCreationBase(
worktreePath,
branch,
baseContext.effectiveBase,
finalizeGitOptions
)
await trackSameNameRemoteBase(
worktreePath,
branch,
baseBranch,
baseContext.effectiveBase,
finalizeGitOptions
)
await configurePushAutoSetupRemote(worktreePath, finalizeGitOptions)
await unlockWorktreePreparationAtPath(
lockPath,
expectedLockReason,
finalizeGitOptions.signal,
operation
)
} catch (error) {
await baseContext.pendingLocalBaseRefRefresh
throw error
}
// Advisory refresh may settle after finalization; it does not determine checkout contents.
const localBaseRefRefresh = await baseContext.pendingLocalBaseRefRefresh
return {
preparedHeadReset,
...(localBaseRefRefresh ? { localBaseRefRefresh } : {}),
...(baseContext.localBaseRefUpdateSuggestion
? { localBaseRefUpdateSuggestion: baseContext.localBaseRefUpdateSuggestion }
: {})
}
})
} finally {
notifyPreparedWorktreeMutation(repoPath)
}
}
@@ -1,6 +1,7 @@
import { canonicalWorktreePath } from '../catalog/worktree-path-comparison'
import type { WorktreePreparationOperation } from './worktree-preparation-operation'
import { readFile, unlink, writeFile } from 'node:fs/promises'
import { posix, win32 } from 'node:path'
import { readFile, realpath, unlink, writeFile } from 'node:fs/promises'
import { dirname, posix, win32 } from 'node:path'
import { isWindowsAbsolutePathLike } from '../../../../shared/cross-platform-path'
import {
resolveGitMetadataPath,
@@ -15,7 +16,10 @@ import {
} from '../worktree-operation-options'
export class WorktreePreparationLockOwnershipError extends Error {
constructor(cause?: unknown) {
constructor(
cause?: unknown,
readonly replaced = false
) {
super('The prepared worktree lock owner changed', { cause })
}
}
@@ -106,10 +110,12 @@ export async function unlockWorktreePreparation(
export async function unlockWorktreePreparationAtPath(
lockPath: string,
expectedLockReason: string,
signal?: AbortSignal
signal?: AbortSignal,
operation?: WorktreePreparationOperation
): Promise<void> {
await verifyWorktreePreparationLockAtPath(lockPath, expectedLockReason, signal)
await unlink(lockPath).catch((error: unknown) => {
const writing = unlink(lockPath)
await (operation ? operation.trackWriter(writing) : writing).catch((error: unknown) => {
throw new WorktreePreparationLockOwnershipError(error)
})
}
@@ -133,7 +139,20 @@ export async function verifyWorktreePreparationLockAtPath(
throw new WorktreePreparationLockOwnershipError(error)
})
if (lockReason !== `${expectedLockReason}\n`) {
throw new WorktreePreparationLockOwnershipError()
throw new WorktreePreparationLockOwnershipError(undefined, true)
}
signal?.throwIfAborted()
}
export async function verifyOriginalPreparationDirectory(
gitDir: string,
originalLockPath: string
): Promise<void> {
const [actual, original] = await Promise.all([
realpath(gitDir),
realpath(dirname(originalLockPath))
])
if (canonicalWorktreePath(actual) !== canonicalWorktreePath(original)) {
throw new WorktreePreparationLockOwnershipError(undefined, true)
}
}
@@ -1,27 +1,20 @@
import {
WorktreePreparationDisposal,
type SettledPreparationDiscard
} from './worktree-preparation-disposal'
import type { PreparationRemovalOutcome } from './worktree-preparation-discard'
import { WorktreePreparationLockOwnershipError } from './worktree-preparation-lock'
import { waitForPromiseWithSignal } from '../../../../shared/abort-signal-reason'
import { sharedPromiseSettlementWaiters } from '../../../../shared/promise-settlement-waiters'
import { GIT_READ_TIMEOUT_MS } from '../../../../shared/git/commands/git-command-timeout'
import { getLocalRepoRefMaintenance } from '../../refs/maintenance/local-repo-ref-maintenance'
import {
resolveWorktreeAddTimeoutMs,
WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
WORKTREE_CREATE_PREPARATION_TTL_MS,
preparationWorkBudget,
type GitWorktreeExecOptions
} from '../worktree-operation-options'
export const WORKTREE_CREATE_PREPARATION_TTL_MS = 5 * 60_000
export { WORKTREE_CREATE_PREPARATION_TTL_MS } from '../worktree-operation-options'
export function preparationWorkBudget(options: GitWorktreeExecOptions, refresh: boolean): number {
const checkout = resolveWorktreeAddTimeoutMs()
const read = options.timeout ?? GIT_READ_TIMEOUT_MS
// Include old-Git registration and direct-WSL read fallbacks, each with its own child budget.
return (
WORKTREE_CREATE_PREPARATION_TTL_MS +
(refresh ? 9 * (options.timeout ?? checkout) : 6 * read + 7 * checkout)
)
}
export class WorktreePreparationOperation {
export class WorktreePreparationOperation extends WorktreePreparationDisposal {
readonly controller = new AbortController()
readonly signal: AbortSignal
private readonly transferred = Promise.withResolvers<void>()
@@ -31,15 +24,17 @@ export class WorktreePreparationOperation {
private timer?: NodeJS.Timeout
private workUntil?: number
private claimed = false
private retirement?: Promise<boolean>
private discardAttempt?: Promise<void>
private retirement?: Promise<void>
private revoked: PreparationRemovalOutcome = 'revoked'
private authorityRevoked = false
private maintenance?: { release: () => void; signal: AbortSignal; finished: boolean }
private discardCheckout?: (options: GitWorktreeExecOptions) => Promise<void>
private discardCheckout?: (options: GitWorktreeExecOptions) => Promise<PreparationRemovalOutcome>
constructor(
private readonly options: GitWorktreeExecOptions,
private readonly expired: () => void = () => {}
) {
super()
this.signal = options.signal
? AbortSignal.any([options.signal, this.controller.signal])
: this.controller.signal
@@ -66,8 +61,12 @@ export class WorktreePreparationOperation {
this.signal.removeEventListener('abort', this.onAbort)
}
setDiscard(discard?: (options: GitWorktreeExecOptions) => Promise<void>): void {
this.discardCheckout = discard
setDiscard(
discard?: (options: GitWorktreeExecOptions) => Promise<PreparationRemovalOutcome>
): void {
if (!this.authorityRevoked || !discard) {
this.discardCheckout = discard
}
}
get isClaimed(): boolean {
@@ -84,7 +83,7 @@ export class WorktreePreparationOperation {
return {
...this.options,
signal: this.signal,
canStart: () => !this.signal.aborted && this.options.canStart?.() !== false,
canStart: () => this.current() && !this.signal.aborted && this.options.canStart?.() !== false,
observeChildTermination: (terminated, writes) => {
this.options.observeChildTermination?.(terminated, writes)
this.observeChildTermination(terminated, writes)
@@ -106,15 +105,22 @@ export class WorktreePreparationOperation {
this.releaseMaintenanceIfSafe()
}
private releaseMaintenanceIfSafe(): void {
const held = this.maintenance
if (held && (held.finished || held.signal.aborted) && this.writers.size === 0) {
private releaseMaintenanceIfSafe(held = this.maintenance): void {
if (
held &&
this.maintenance === held &&
(held.finished || held.signal.aborted) &&
this.writers.size === 0
) {
held.release()
this.maintenance = undefined
}
}
async withMaintenancePaused<T>(run: () => Promise<T>, signal = this.signal): Promise<T> {
async withMaintenancePaused<T>(
run: () => Promise<T>,
signal: AbortSignal | undefined = this.signal
): Promise<T> {
const acquiring = getLocalRepoRefMaintenance().pause('worktree-prepare')
const release = await waitForPromiseWithSignal(acquiring, signal).catch((error: unknown) => {
void acquiring.then(
@@ -123,20 +129,28 @@ export class WorktreePreparationOperation {
)
throw error
})
return this.runWithMaintenanceLease(run, release, signal)
}
private async runWithMaintenanceLease<T>(
run: () => Promise<T>,
release: () => void,
signal: AbortSignal
): Promise<T> {
if (signal.aborted) {
release()
signal.throwIfAborted()
}
const held = { release, signal, finished: false }
this.maintenance = held
const onAbort = (): void => this.releaseMaintenanceIfSafe()
const onAbort = (): void => this.releaseMaintenanceIfSafe(held)
signal.addEventListener('abort', onAbort, { once: true })
try {
return await run()
} finally {
held.finished = true
signal.removeEventListener('abort', onAbort)
this.releaseMaintenanceIfSafe()
this.releaseMaintenanceIfSafe(held)
}
}
@@ -160,7 +174,9 @@ export class WorktreePreparationOperation {
this.signal.throwIfAborted()
} catch (error) {
if (error instanceof WorktreePreparationLockOwnershipError) {
this.authorityRevoked = true
this.setDiscard(undefined)
this.revoked = error.replaced ? 'ownership-lost' : 'revoked'
}
this.controller.abort(error)
throw error
@@ -192,107 +208,114 @@ export class WorktreePreparationOperation {
this.timer.unref()
}
retire(): Promise<boolean> {
if (this.retirement) {
return this.retirement
supervise<T>(
options: GitWorktreeExecOptions,
work: (options: GitWorktreeExecOptions) => Promise<T>,
rollback = false
): Promise<T> {
if (!rollback) {
this.signal.throwIfAborted()
}
this.controller.abort()
const proof = this.raw
this.complete()
this.beginFinalization(rollback)
this.retirement = undefined
let eligible = true
const result = Promise.resolve()
.then(() =>
work({
...options,
canStart: () => eligible && this.current() && options.canStart?.() !== false,
observeChildTermination: (terminated, writes) => {
options.observeChildTermination?.(terminated, writes)
this.observeChildTermination(terminated, writes)
}
})
)
.catch((error: unknown) => {
if (error instanceof WorktreePreparationLockOwnershipError) {
this.authorityRevoked = true
this.setDiscard(undefined)
this.revoked = error.replaced ? 'ownership-lost' : 'revoked'
}
throw error
})
.finally(() => {
eligible = false
})
this.raw = result.then(
() => {},
() => {}
)
return result
}
physicalSettlement(): Promise<void> {
return this.raw
.catch(() => {})
.then(async () => {
await Promise.allSettled(this.writers)
})
this.retirement = sharedPromiseSettlementWaiters(proof)
.wait({
timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS
})
.then(
() => true,
() => false
)
}
retire(): Promise<void> {
if (!this.retirement) {
this.controller.abort()
this.retirement = this.physicalSettlement()
}
return this.retirement
}
discard(): Promise<void> {
if (!this.discardAttempt) {
this.discardAttempt = this.discardOnce()
void this.discardAttempt.catch(() => {
this.discardAttempt = undefined
})
}
return this.discardAttempt
}
private async discardOnce(): Promise<void> {
if (!(await this.retire())) {
return
}
protected async physicalDiscard(
eligible: () => boolean,
before: () => Promise<boolean>,
leaseRetirement: AbortSignal
): Promise<SettledPreparationDiscard> {
const discard = this.discardCheckout
if (!discard) {
return
return { status: this.revoked, attempted: false }
}
let eligible = true
const cleanupController = new AbortController()
const cleanup = this.withMaintenancePaused(
() =>
discard({
...this.options,
signal: undefined,
canStart: () => eligible,
observeChildTermination: this.observeChildTermination
}),
cleanupController.signal
)
// A rejection is not physical completion; retries also require all writer receipts.
const settled = cleanup
.then(
() => ({ error: undefined }),
(error: unknown) => ({ error })
let attempted = false
// Lease retirement cannot replace the original acquisition's physical settlement.
const acquiring = getLocalRepoRefMaintenance().pause('worktree-prepare')
const cleanup = acquiring.then((release) =>
this.runWithMaintenanceLease(
async () => {
if (!eligible() || !(await before()) || !eligible()) {
return 'skipped' as const
}
return discard({
...this.options,
admissionTier: 'background',
signal: undefined,
canStart: eligible,
observeChildTermination: (terminated, writes) => {
if (writes) {
attempted = true
}
this.observeChildTermination(terminated, writes)
}
})
},
release,
leaseRetirement
)
.then(async (result) => {
await Promise.allSettled(this.writers)
return result
)
const result = await cleanup.then(
(status): SettledPreparationDiscard => ({ status, attempted }),
(error: unknown): SettledPreparationDiscard => ({
status:
!eligible() && !attempted
? 'skipped'
: error instanceof WorktreePreparationLockOwnershipError
? error.replaced
? 'ownership-lost'
: 'revoked'
: 'failed',
attempted: attempted || eligible(),
error
})
try {
const result = await sharedPromiseSettlementWaiters(settled).wait({
timeoutMs: WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS,
onAbandon: () => {
eligible = false
cleanupController.abort()
}
})
if (result.error !== undefined) {
throw result.error
}
} catch (error) {
if (!eligible) {
this.retirement = Promise.resolve(false)
return
}
throw error
} finally {
eligible = false
}
}
}
export async function runStandalonePreparation<T>(
options: GitWorktreeExecOptions,
work: (operation: WorktreePreparationOperation) => Promise<T>
): Promise<T> {
const operation = new WorktreePreparationOperation(options)
// A direct caller still owns its fetch barrier; only pool handoff supersedes it.
operation.claim(false)
let result!: T
try {
await operation.run(async () => {
result = await work(operation)
})
return result
} catch (error) {
await operation.discard().catch(() => {})
throw error
} finally {
operation.complete()
)
await Promise.allSettled(this.writers)
return { ...result, attempted: result.attempted || attempted }
}
}
@@ -0,0 +1,23 @@
import type { GitWorktreeExecOptions } from '../worktree-operation-options'
import { WorktreePreparationOperation } from './worktree-preparation-operation'
export async function runStandalonePreparation<T>(
options: GitWorktreeExecOptions,
work: (operation: WorktreePreparationOperation) => Promise<T>
): Promise<T> {
const operation = new WorktreePreparationOperation(options)
// A direct caller still owns its fetch barrier; only pool handoff supersedes it.
operation.claim(false)
let result!: T
try {
await operation.run(async () => {
result = await work(operation)
})
return result
} catch (error) {
await operation.discard().catch(() => {})
throw error
} finally {
operation.complete()
}
}
@@ -1,3 +1,6 @@
import { randomUUID } from 'node:crypto'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
// Worktree add/move/remove/rollback rewrite the `.git` marker the WSL Git route was derived from.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
@@ -57,8 +60,8 @@ vi.mock('../catalog/worktree-scan-cache', () => ({
vi.mock('../creation/worktree-preparation-lock', async (importOriginal) => ({
...(await importOriginal<typeof WorktreePreparationLock>()),
lockWorktreePreparation: vi.fn(async () => '/owned-lock'),
verifyWorktreePreparationLock: vi.fn(async () => '/owned-lock'),
lockWorktreePreparation: vi.fn(async () => ownedLockPath),
verifyWorktreePreparationLock: vi.fn(async () => ownedLockPath),
verifyWorktreePreparationLockAtPath: vi.fn(),
unlockWorktreePreparationAtPath: vi.fn()
}))
@@ -77,6 +80,8 @@ import {
usesHostGitForWslLinkedWorktree
} from '../../command-runner/wsl-linked-worktree-git-routing'
const ownedLockPath = join(tmpdir(), `orca-route-invalidation-${randomUUID()}`, 'locked')
const REPO = String.raw`C:\repo`
const LINKED = String.raw`C:\ws\linked`
const MOVED = String.raw`C:\ws\moved`
@@ -1,3 +1,4 @@
import { GIT_READ_TIMEOUT_MS } from '../../../shared/git/commands/git-command-timeout'
import type {
LocalBaseRefRefreshResult,
LocalBaseRefUpdateSuggestion
@@ -63,6 +64,18 @@ export const WORKTREE_REMOVAL_REGISTRATION_TIMEOUT_MS = 30_000
// A wedged shared scan would otherwise stall every later listing.
export const WORKTREE_LIST_TIMEOUT_MS = 30_000
export const WORKTREE_CREATE_PREPARATION_TTL_MS = 5 * 60_000
export function preparationWorkBudget(options: GitWorktreeExecOptions, refresh: boolean): number {
const checkout = resolveWorktreeAddTimeoutMs()
const read = options.timeout ?? GIT_READ_TIMEOUT_MS
// Include old-Git registration and direct-WSL read fallbacks, each with its own child budget.
return (
WORKTREE_CREATE_PREPARATION_TTL_MS +
(refresh ? 9 * (options.timeout ?? checkout) : 6 * read + 7 * checkout)
)
}
/** Clamp ORCA_WORKTREE_ADD_TIMEOUT_MS; warn for nonblank rejected/clamped values, not fractional truncation. */
export function resolveWorktreeAddTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {
const raw = env.ORCA_WORKTREE_ADD_TIMEOUT_MS?.trim()
@@ -117,18 +117,3 @@ it.each(['owner', 'same-text rename'] as const)(
)
}
)
it('uses current naming settings if they change while the title write is queued', async () => {
let eligible = true
const generate = vi.fn<StructuredChatNamingDeps['generate']>(
async (_record, _prompt, _current, automatic) =>
automatic ? { name: 'CLI title', shouldApply: () => eligible } : { name: 'Configured title' }
)
const state = rig(generate)
state.beforeWrite(async () => {
eligible = false
})
state.start()
await state.done()
expect(state.record().conversationName).toBe('Configured title')
})
@@ -7,7 +7,6 @@ import {
symlinkDirectorySync
} from '../persistence-test-harness'
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { getFloatingWorkspaceFileRoots } from '../../ipc/floating-workspace-directory'
import { rmSync, mkdtempSync, mkdirSync, realpathSync } from 'node:fs'
import { join } from 'node:path'
import { tmpdir } from 'node:os'
@@ -92,27 +91,6 @@ describe('floating workspace trust on load', () => {
})
})
it('still loads a profile whose floating cwd is not a string', async () => {
writeDataFile({
schemaVersion: 1,
repos: [],
worktreeMeta: {},
settings: {
floatingTerminalCwd: 42,
floatingTerminalCwdMigratedToAppWorkspace: true
},
ui: {},
githubCache: { pr: {}, issue: {} },
workspaceSession: {}
})
const store = await createStore()
expect(store.getSettings().floatingTerminalCwd).toBe('~')
// File authorization reads the cwd on every check, so it must keep working for this profile.
expect(getFloatingWorkspaceFileRoots(store).exactRoots).toEqual([])
})
it('never re-points a trusted folder through a link on load', async () => {
const trustedTarget = join(testState.dir, 'trusted-target')
const trustedLink = join(testState.dir, 'trusted-link')
@@ -3,7 +3,7 @@ import {
dispatchAssigneeCoordinatorKey,
selectRunBoundDispatchRecipient
} from '../../rpc/methods/orchestration/messaging/recipient-routing'
import { federatedControlMailRefusal } from '../../rpc/methods/orchestration/messaging/send-control-mail'
import { federatedControlMailRefusal } from '../legacy-remote-home/legacy-remote-home'
import type { createLineageRunningSessionResolver } from '../addressing/session-lineage/structured-session-lineage'
import type { DispatchInput } from './crew-recipient-owner-queries'
import type { CrewRecipientTerminal } from './crew-recipient-inputs'
@@ -7,17 +7,9 @@ import { attachDispatchContextStore } from './dispatch-context/dispatch-context-
import { attachDispatchLookup } from './dispatch-context/dispatch-lookup'
import { attachDispatchDepth } from './dispatch-depth'
import { attachWorkerReportSettlement } from './dispatch-context/worker-report-settlement'
import { attachFederatedDispatchStore } from './federation/federated-dispatch-store'
import { attachFederatedDispatchObservationFence } from './federation/federated-dispatch-observation-fence'
import { attachFederationRelayAck } from './federation/federation-relay-ack'
import { attachFederationRelayEnqueue } from './federation/federation-relay-enqueue'
import { attachFederationRelayImport } from './federation/federation-relay-import'
import { attachFederationRelayItem } from './federation/federation-relay-item'
import { attachRemoteDispatchAttachmentAuthority } from './federation/remote-dispatch-attachment-authority'
import { attachRemoteDispatchAttachmentCreate } from './federation/remote-dispatch-attachment-create'
import { attachRemoteDispatchAttachmentRelease } from './federation/remote-dispatch-attachment-release'
import { attachRemoteDispatchAttachmentStop } from './federation/remote-dispatch-attachment-stop'
import { attachRemoteQuestionStore } from './federation/remote-question-store'
import { attachLegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods'
import { attachLegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods'
import { attachPeerMailStore } from './federation/peer-mail-store'
import { attachLegacyAskOperation } from './legacy/legacy-ask-operation'
import { attachLegacyCompatibilityCandidates } from './legacy/legacy-compatibility-candidates'
@@ -54,7 +46,6 @@ import { attachSchemaMigrate } from './schema/migrate'
import { attachSchemaColumnProbes } from './schema/schema-column-probes'
import { attachTaskStore } from './tasks/task-store'
import { attachTaskStatusTransition } from './tasks/task-status-transition'
import { attachFederatedWorkerStartReconcile } from './worker-dispatch/federated-worker-start-reconcile'
import { attachWorkerDispatchAbandon } from './worker-dispatch/worker-dispatch-abandon'
import { attachWorkerDispatchAuthority } from './worker-dispatch/worker-dispatch-authority'
import { attachWorkerDispatchOutcome } from './worker-dispatch/worker-dispatch-outcome'
@@ -109,22 +100,13 @@ export function attachOrchestrationDbMethods(ctor: { prototype: object }): void
attachWorkerDispatchStage(ctor)
attachWorkerDispatchAuthority(ctor)
attachWorkerDispatchOutcome(ctor)
attachFederatedWorkerStartReconcile(ctor)
attachWorkerTerminalRecovery(ctor)
attachWorkerDispatchStop(ctor)
attachWorkerDispatchAbandon(ctor)
attachFederatedDispatchStore(ctor)
attachFederatedDispatchObservationFence(ctor)
attachRemoteDispatchAttachmentCreate(ctor)
attachRemoteDispatchAttachmentAuthority(ctor)
attachRemoteDispatchAttachmentRelease(ctor)
attachRemoteDispatchAttachmentStop(ctor)
attachFederationRelayEnqueue(ctor)
attachLegacyRemoteHomeDbMethods(ctor)
attachLegacyRemoteDbMethods(ctor)
attachFederationRelayAck(ctor)
attachFederationRelayImport(ctor)
attachRemoteQuestionStore(ctor)
attachPeerMailStore(ctor)
attachFederationRelayItem(ctor)
attachWorkerTerminalResourceStore(ctor)
attachWorkerTerminalTransfer(ctor)
attachWorkerTerminalRelease(ctor)
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { parseFederatedWorkerReportOutcome } from './federated-worker-report-outcome'
import { parseFederatedWorkerReportOutcome } from '../legacy-remote/federated-worker-report-outcome'
describe('federated-worker-report-outcome', () => {
it('reads succeeded or failed from a nested report payload', () => {
@@ -1,36 +1,7 @@
import type {
WorkerReportOutcome,
FederationRelayDirection,
FederationRelayItemRow
} from '../orchestration-records'
import { OrchestrationError } from '../../orchestration-error'
import { ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION } from '../../../../../shared/orchestration/orchestration-runtime-capabilities'
import { parseFederatedWorkerReportOutcome } from '../federated-worker-report-outcome'
import type { FederationRelayDirection, FederationRelayItemRow } from '../orchestration-records'
import type { FederationRelayAcknowledgment } from '../../legacy-remote/legacy-remote-db-methods'
import type { OrchestrationDb } from '../orchestration-db'
export function listFederationRelay(
this: OrchestrationDb,
params: {
dispatchId: string
direction: FederationRelayDirection
afterSequence: number
limit?: number
}
): FederationRelayItemRow[] {
return this.db
.prepare(
`SELECT * FROM federation_relay_items
WHERE dispatch_id = ? AND direction = ? AND sequence > ?
ORDER BY sequence LIMIT ?`
)
.all(
params.dispatchId,
params.direction,
params.afterSequence,
Math.min(Math.max(params.limit ?? 50, 1), 50)
) as FederationRelayItemRow[]
}
export function listPendingFederationRelay(
this: OrchestrationDb,
dispatchId: string,
@@ -48,78 +19,11 @@ export function listPendingFederationRelay(
export function acknowledgeFederationRelay(
this: OrchestrationDb,
params: {
dispatchId: string
direction: FederationRelayDirection
throughSequence: number
settleRemoteReports?: { sequence: number; outcome?: WorkerReportOutcome }[]
// Only the home's acceptance proves settlement; arm after it, never at queue time.
armAutoRelease?: boolean
}
params: FederationRelayAcknowledgment
): void {
this.db.exec('BEGIN IMMEDIATE')
try {
const settledReports = params.settleRemoteReports ?? []
for (const settledReport of settledReports) {
const report = this.getFederationRelayItem(
params.dispatchId,
params.direction,
settledReport.sequence
)
if (
params.direction !== 'to_home' ||
settledReport.sequence > params.throughSequence ||
report?.kind !== 'worker_done' ||
(settledReport.outcome !== undefined &&
parseFederatedWorkerReportOutcome(report.payload) !== settledReport.outcome)
) {
throw new OrchestrationError(
'request_mismatch',
`Federation acknowledgment for ${params.dispatchId} does not match its queued worker_done.`
)
}
}
const attachment = this.getRemoteDispatchAttachment(params.dispatchId)
if (
params.direction === 'to_home' &&
attachment !== undefined &&
attachment.protocol_version >= ORCHESTRATION_FEDERATION_LIFECYCLE_SETTLEMENT_PROTOCOL_VERSION
) {
const acknowledgedReports = this.db
.prepare(
`SELECT sequence FROM federation_relay_items
WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done'
AND acked_at IS NULL AND sequence <= ?`
)
.all(params.dispatchId, params.throughSequence) as { sequence: number }[]
const settledSequences = new Set(settledReports.map((report) => report.sequence))
if (acknowledgedReports.some((report) => !settledSequences.has(report.sequence))) {
throw new OrchestrationError(
'request_mismatch',
`Federation acknowledgment for ${params.dispatchId} omits a worker_done settlement.`
)
}
}
const terminalOutcomes = new Set(
settledReports.flatMap((report) => (report.outcome ? [report.outcome] : []))
)
if (terminalOutcomes.size > 1) {
throw new OrchestrationError(
'request_mismatch',
`Federation acknowledgment for ${params.dispatchId} contains conflicting settlements.`
)
}
const terminalOutcome = settledReports.find((report) => report.outcome)?.outcome
if (terminalOutcome) {
this.settleRemoteAttachmentInRelayTransaction(
params.dispatchId,
terminalOutcome,
'worker_report_settled'
)
if (params.armAutoRelease) {
this.armWorkerTerminalAutoReleaseStatement(params.dispatchId)
}
}
this.settleRemoteReportsInRelayAcknowledgment(params)
this.db
.prepare(
`UPDATE federation_relay_items SET acked_at = COALESCE(acked_at, datetime('now'))
@@ -133,93 +37,14 @@ export function acknowledgeFederationRelay(
}
}
export function setFederatedHomeImportSequence(
this: OrchestrationDb,
dispatchId: string,
sequence: number
): void {
this.db
.prepare(
`UPDATE federated_dispatches
SET to_home_imported_sequence = ?, updated_at = datetime('now')
WHERE dispatch_id = ? AND to_home_imported_sequence < ?`
)
.run(sequence, dispatchId, sequence)
}
export function recordFederatedHomeAcknowledgment(
this: OrchestrationDb,
params: {
dispatchId: string
remoteRuntimeEpoch: string
sequence: number
}
): void {
const federated = this.getFederatedDispatch(params.dispatchId)
if (
!federated ||
!Number.isInteger(params.sequence) ||
params.sequence < 0 ||
params.sequence > federated.to_home_imported_sequence
) {
throw new OrchestrationError(
'request_mismatch',
`Federation acknowledgment for ${params.dispatchId} exceeds imported relay state.`
)
}
this.db
.prepare(
`UPDATE federated_dispatches
SET remote_runtime_epoch = ?,
to_home_acknowledged_sequence = CASE
WHEN remote_runtime_epoch = ?
THEN MAX(to_home_acknowledged_sequence, ?)
ELSE ?
END,
updated_at = datetime('now')
WHERE dispatch_id = ?`
)
.run(
params.remoteRuntimeEpoch,
params.remoteRuntimeEpoch,
params.sequence,
params.sequence,
params.dispatchId
)
}
/** A worker_done queued for the Run home that it has not acknowledged. */
export function hasPendingFederatedWorkerReport(
this: OrchestrationDb,
dispatchId: string
): boolean {
return (
this.db
.prepare(
`SELECT 1 FROM federation_relay_items
WHERE dispatch_id = ? AND direction = 'to_home' AND kind = 'worker_done'
AND acked_at IS NULL LIMIT 1`
)
.get(dispatchId) !== undefined
)
}
export type FederationRelayAckMethods = {
listFederationRelay: typeof listFederationRelay
listPendingFederationRelay: typeof listPendingFederationRelay
acknowledgeFederationRelay: typeof acknowledgeFederationRelay
setFederatedHomeImportSequence: typeof setFederatedHomeImportSequence
recordFederatedHomeAcknowledgment: typeof recordFederatedHomeAcknowledgment
hasPendingFederatedWorkerReport: typeof hasPendingFederatedWorkerReport
}
export function attachFederationRelayAck(ctor: { prototype: object }): void {
Object.assign(ctor.prototype, {
listFederationRelay,
listPendingFederationRelay,
acknowledgeFederationRelay,
setFederatedHomeImportSequence,
recordFederatedHomeAcknowledgment,
hasPendingFederatedWorkerReport
acknowledgeFederationRelay
})
}
@@ -6,17 +6,9 @@ import type { DispatchContextStoreMethods } from './dispatch-context/dispatch-co
import type { DispatchLookupMethods } from './dispatch-context/dispatch-lookup'
import type { DispatchDepthMethods } from './dispatch-depth'
import type { WorkerReportSettlementMethods } from './dispatch-context/worker-report-settlement'
import type { FederatedDispatchStoreMethods } from './federation/federated-dispatch-store'
import type { FederatedDispatchObservationFenceMethods } from './federation/federated-dispatch-observation-fence'
import type { FederationRelayAckMethods } from './federation/federation-relay-ack'
import type { FederationRelayEnqueueMethods } from './federation/federation-relay-enqueue'
import type { FederationRelayImportMethods } from './federation/federation-relay-import'
import type { FederationRelayItemMethods } from './federation/federation-relay-item'
import type { RemoteDispatchAttachmentAuthorityMethods } from './federation/remote-dispatch-attachment-authority'
import type { RemoteDispatchAttachmentCreateMethods } from './federation/remote-dispatch-attachment-create'
import type { RemoteDispatchAttachmentReleaseMethods } from './federation/remote-dispatch-attachment-release'
import type { RemoteDispatchAttachmentStopMethods } from './federation/remote-dispatch-attachment-stop'
import type { RemoteQuestionStoreMethods } from './federation/remote-question-store'
import type { LegacyRemoteDbMethods } from '../legacy-remote/legacy-remote-db-methods'
import type { LegacyRemoteHomeDbMethods } from '../legacy-remote-home/legacy-remote-home-db-methods'
import type { PeerMailStoreMethods } from './federation/peer-mail-store'
import type { LegacyAskOperationMethods } from './legacy/legacy-ask-operation'
import type { LegacyCompatibilityCandidatesMethods } from './legacy/legacy-compatibility-candidates'
@@ -52,7 +44,6 @@ import type { SchemaMigrateMethods } from './schema/migrate'
import type { SchemaColumnProbesMethods } from './schema/schema-column-probes'
import type { TaskStoreMethods } from './tasks/task-store'
import type { TaskStatusTransitionMethods } from './tasks/task-status-transition'
import type { FederatedWorkerStartReconcileMethods } from './worker-dispatch/federated-worker-start-reconcile'
import type { WorkerDispatchAbandonMethods } from './worker-dispatch/worker-dispatch-abandon'
import type { WorkerDispatchAuthorityMethods } from './worker-dispatch/worker-dispatch-authority'
import type { WorkerDispatchOutcomeMethods } from './worker-dispatch/worker-dispatch-outcome'
@@ -106,22 +97,13 @@ export type OrchestrationDbMethods = AttemptObservationStoreMethods &
WorkerDispatchStageMethods &
WorkerDispatchAuthorityMethods &
WorkerDispatchOutcomeMethods &
FederatedWorkerStartReconcileMethods &
WorkerTerminalRecoveryMethods &
WorkerDispatchStopMethods &
WorkerDispatchAbandonMethods &
FederatedDispatchStoreMethods &
FederatedDispatchObservationFenceMethods &
RemoteDispatchAttachmentCreateMethods &
RemoteDispatchAttachmentAuthorityMethods &
RemoteDispatchAttachmentReleaseMethods &
RemoteDispatchAttachmentStopMethods &
FederationRelayEnqueueMethods &
LegacyRemoteHomeDbMethods &
LegacyRemoteDbMethods &
FederationRelayAckMethods &
FederationRelayImportMethods &
RemoteQuestionStoreMethods &
PeerMailStoreMethods &
FederationRelayItemMethods &
StructuredMailSendStoreMethods &
WorkerTerminalResourceStoreMethods &
WorkerTerminalTransferMethods &
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { OrchestrationDb } from '../orchestration-db'
import { SCHEMA_VERSION, federatedStubHomeRunId } from '../contract-constants'
import { importFederatedControlMessage } from '../../federation/relay/federation-control-message'
import { importFederatedControlMessage } from '../../legacy-remote/federation-control-message'
describe('federated home Run migration', () => {
let db: OrchestrationDb
@@ -174,72 +174,6 @@ export function admitWorkerChatReleaseClose(
return changes > 0
}
/** Only for a host that cannot release on its own; arms once, so a retain or release before settlement still wins. */
export function armFederatedHomeAutoRelease(
this: OrchestrationDb,
dispatchId: string,
nowMs = Date.now()
): void {
const { changes } = this.db
.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = ?, home_auto_release_state = 'armed', updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state IS NULL`
)
.run(toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS), dispatchId)
if (changes > 0) {
this.workerTerminalAutoReleaseListener?.()
}
}
/** A retain, an explicit release or the host's answer to an attempt ends the home deadline for good. */
export function endFederatedHomeAutoRelease(this: OrchestrationDb, dispatchId: string): void {
this.db
.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = NULL, home_auto_release_state = 'ended', updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state IS NOT 'ended'`
)
.run(dispatchId)
}
/** Claiming postpones the deadline instead of hiding it, so an attempt cut short by a crash or failure runs again. */
export function claimDueFederatedHomeAutoReleases(this: OrchestrationDb, nowMs: number): string[] {
if (this.workerAutoReleaseEnabled?.() === false) {
return []
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT names exactly this one column.
const due = this.db
.prepare(
`SELECT dispatch_id FROM federated_dispatches
WHERE home_auto_release_state = 'armed' AND home_auto_release_at <= ?`
)
.all(toSqliteUtcTimestamp(nowMs)) as { dispatch_id: string }[]
const claim = this.db.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = ?, updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state = 'armed' AND home_auto_release_at <= ?`
)
const retryAt = toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS)
return due.flatMap(({ dispatch_id }) =>
claim.run(retryAt, dispatch_id, toSqliteUtcTimestamp(nowMs)).changes > 0 ? [dispatch_id] : []
)
}
export function isFederatedHomeAutoReleaseArmed(
this: OrchestrationDb,
dispatchId: string
): boolean {
return (
this.db
.prepare(
`SELECT 1 FROM federated_dispatches
WHERE dispatch_id = ? AND home_auto_release_state = 'armed'`
)
.get(dispatchId) !== undefined
)
}
export function nextWorkerTerminalAutoReleaseAtMs(this: OrchestrationDb): number | null {
// Off: nothing is due, so no timer runs until the setting turns back on.
if (this.workerAutoReleaseEnabled?.() === false) {
@@ -276,10 +210,6 @@ export type WorkerTerminalAutoReleaseMethods = {
claimDueWorkerTerminalAutoReleases: typeof claimDueWorkerTerminalAutoReleases
admitWorkerChatReleaseClose: typeof admitWorkerChatReleaseClose
nextWorkerTerminalAutoReleaseAtMs: typeof nextWorkerTerminalAutoReleaseAtMs
armFederatedHomeAutoRelease: typeof armFederatedHomeAutoRelease
endFederatedHomeAutoRelease: typeof endFederatedHomeAutoRelease
claimDueFederatedHomeAutoReleases: typeof claimDueFederatedHomeAutoReleases
isFederatedHomeAutoReleaseArmed: typeof isFederatedHomeAutoReleaseArmed
}
export function attachWorkerTerminalAutoRelease(ctor: { prototype: object }): void {
@@ -291,10 +221,6 @@ export function attachWorkerTerminalAutoRelease(ctor: { prototype: object }): vo
deferWorkerTerminalAutoRelease,
claimDueWorkerTerminalAutoReleases,
admitWorkerChatReleaseClose,
nextWorkerTerminalAutoReleaseAtMs,
armFederatedHomeAutoRelease,
endFederatedHomeAutoRelease,
claimDueFederatedHomeAutoReleases,
isFederatedHomeAutoReleaseArmed
nextWorkerTerminalAutoReleaseAtMs
})
}
@@ -1,7 +1,7 @@
import type { RuntimeRequestPreparation } from '../../../../../shared/runtime-rpc-envelope'
import { REMOTE_RUNTIME_MAX_INBOUND_REQUEST_JSON_BYTES } from '../../../../../shared/remote-runtime/remote-runtime-memory-limits'
import { OrchestrationError } from '../../orchestration-error'
import type { federationRelayWireItem } from './federation-relay-wire'
import type { federationRelayWireItem } from '../../legacy-remote/legacy-remote'
/** Fit only this already-selected page, using the actual sending socket's complete serializer. */
export function federationRelayPrefix(
@@ -19,16 +19,16 @@ import type {
import { OrchestrationError } from '../orchestration-error'
import {
clearFederationAckCheckpoints,
releaseFederationAckCheckpoint
} from './synchronization/federation-ack-checkpoints'
import { syncFederatedDispatch } from './synchronization/federation-sync'
releaseFederationAckCheckpoint,
syncFederatedDispatch,
FederationAcknowledgmentRecovery
} from '../legacy-remote-home/legacy-remote-home'
import type { OrchestrationDb } from '../db/orchestration-db'
import type { FederationRuntime } from './federation-runtime'
import {
FederationRelayScheduler,
type FederationRelayTickOutcome
} from './relay/federation-relay-scheduler'
import { FederationAcknowledgmentRecovery } from './relay/federation-acknowledgment-recovery'
export class RuntimeOrchestrationFederation {
private readonly relays = new FederationRelayScheduler((dispatchId) => this.relayTick(dispatchId))
@@ -6,7 +6,7 @@ import {
getFederationAckedThrough,
recordFederationAckCheckpoint,
type FederationAckIdentity
} from './federation-ack-checkpoints'
} from '../../legacy-remote-home/federation-ack-checkpoints'
describe('federation acknowledgment checkpoints', () => {
it('matches checkpoints only to their exact remote identity and never moves backward', () => {
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest'
import { ORCHESTRATION_FEDERATION_RELEASE_ARCHIVE_RUNTIME_CAPABILITY } from '../../../../../shared/orchestration/orchestration-runtime-capabilities'
import { createIdleSyncHarness } from './federation-sync-test-harness'
import { armHomeAutoReleaseForOlderHost } from './federation-sync-capability'
import { armHomeAutoReleaseForOlderHost } from '../../legacy-remote-home/federation-sync-capability'
function releasableTerminalWorker() {
const harness = createIdleSyncHarness()
@@ -0,0 +1,89 @@
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
import { dirname, join, relative, resolve, sep } from 'node:path'
import { describe, expect, it } from 'vitest'
const SRC = resolve(import.meta.dirname, '../../..')
// Each folder has one entry module, plus a DB-only one so the DB layer never loads rpc code.
// The two folders are one frozen unit and may import each other directly.
const DB_LAYER = 'main/runtime/orchestration/db/'
const LEGACY_ENTRIES_BY_FOLDER = {
'main/runtime/orchestration/legacy-remote/': {
entry: 'main/runtime/orchestration/legacy-remote/legacy-remote.ts',
dbEntry: 'main/runtime/orchestration/legacy-remote/legacy-remote-db-methods.ts'
},
'main/runtime/orchestration/legacy-remote-home/': {
entry: 'main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts',
dbEntry: 'main/runtime/orchestration/legacy-remote-home/legacy-remote-home-db-methods.ts'
}
}
// Legacy starts load the worker list, so it bypasses the entry module to stay out of an import cycle.
const DIRECT_IMPORTS = new Set([
'main/runtime/rpc/methods/orchestration/worker/worker-list-projection.ts -> main/runtime/orchestration/legacy-remote-home/federated-fleet-snapshot.ts'
])
const IMPORT_SPECIFIER =
/(?:from\s+|import\s*\(\s*|import\s+|require\(\s*)['"](\.{1,2}\/[^'"]+)['"]/g
function productionSources(dir: string, out: string[] = []): string[] {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const path = join(dir, entry.name)
if (entry.isDirectory()) {
if (entry.name !== 'node_modules') {
productionSources(path, out)
}
} else if (
/\.tsx?$/.test(entry.name) &&
!/\.(test|spec)\.|test-support|harness/.test(entry.name)
) {
out.push(path)
}
}
return out
}
function srcPath(file: string): string {
return relative(SRC, file).split(sep).join('/')
}
function resolveSpecifier(fromFile: string, specifier: string): string | undefined {
const base = resolve(dirname(fromFile), specifier)
return [base, `${base}.ts`, `${base}.tsx`, join(base, 'index.ts')].find(
(candidate) => existsSync(candidate) && statSync(candidate).isFile()
)
}
describe('legacy remote-attachment folders', () => {
it('are imported from outside only through their entry module', () => {
const violations: string[] = []
const entryImporters = new Set<string>()
for (const file of productionSources(SRC)) {
const from = srcPath(file)
for (const match of readFileSync(file, 'utf8').matchAll(IMPORT_SPECIFIER)) {
const target = resolveSpecifier(file, match[1])
if (!target) {
continue
}
const to = srcPath(target)
for (const [folder, { entry, dbEntry }] of Object.entries(LEGACY_ENTRIES_BY_FOLDER)) {
if (
to.startsWith(folder) &&
!Object.keys(LEGACY_ENTRIES_BY_FOLDER).some((f) => from.startsWith(f))
) {
if (to === entry || (to === dbEntry && from.startsWith(DB_LAYER))) {
entryImporters.add(`${from} -> ${to}`)
} else if (!DIRECT_IMPORTS.has(`${from} -> ${to}`)) {
violations.push(`${from} -> ${to}`)
}
}
}
}
}
expect(violations).toEqual([])
// The capability branch on each side: legacy worker starts and the legacy federation methods.
expect(entryImporters).toContain(
'main/runtime/rpc/methods/orchestration/worker/workers.ts -> main/runtime/orchestration/legacy-remote-home/legacy-remote-home.ts'
)
expect(entryImporters).toContain(
'main/runtime/rpc/methods/orchestration/federation/federation-methods.ts -> main/runtime/orchestration/legacy-remote/legacy-remote.ts'
)
})
})
@@ -1,4 +1,4 @@
import type { OrchestrationWorkerLaunchReceipt } from '../worker/worker-launch-preferences'
import type { OrchestrationWorkerLaunchReceipt } from '../../rpc/methods/orchestration/worker/worker-launch-preferences'
export type RemoteFederatedWorkerStartReceipt = {
dispatchId: string
@@ -1,6 +1,6 @@
import type { FederatedDispatchRow } from '../orchestration-records'
import { OrchestrationError } from '../../orchestration-error'
import type { OrchestrationDb } from '../orchestration-db'
import type { FederatedDispatchRow } from '../db/orchestration-records'
import { OrchestrationError } from '../orchestration-error'
import type { OrchestrationDb } from '../db/orchestration-db'
export function getFederatedDispatch(
this: OrchestrationDb,
@@ -125,6 +125,61 @@ export function updateFederatedDispatchRuntimeEpoch(
.run(remoteRuntimeEpoch, dispatchId, remoteRuntimeEpoch)
}
export function setFederatedHomeImportSequence(
this: OrchestrationDb,
dispatchId: string,
sequence: number
): void {
this.db
.prepare(
`UPDATE federated_dispatches
SET to_home_imported_sequence = ?, updated_at = datetime('now')
WHERE dispatch_id = ? AND to_home_imported_sequence < ?`
)
.run(sequence, dispatchId, sequence)
}
export function recordFederatedHomeAcknowledgment(
this: OrchestrationDb,
params: {
dispatchId: string
remoteRuntimeEpoch: string
sequence: number
}
): void {
const federated = this.getFederatedDispatch(params.dispatchId)
if (
!federated ||
!Number.isInteger(params.sequence) ||
params.sequence < 0 ||
params.sequence > federated.to_home_imported_sequence
) {
throw new OrchestrationError(
'request_mismatch',
`Federation acknowledgment for ${params.dispatchId} exceeds imported relay state.`
)
}
this.db
.prepare(
`UPDATE federated_dispatches
SET remote_runtime_epoch = ?,
to_home_acknowledged_sequence = CASE
WHEN remote_runtime_epoch = ?
THEN MAX(to_home_acknowledged_sequence, ?)
ELSE ?
END,
updated_at = datetime('now')
WHERE dispatch_id = ?`
)
.run(
params.remoteRuntimeEpoch,
params.remoteRuntimeEpoch,
params.sequence,
params.sequence,
params.dispatchId
)
}
export type FederatedDispatchStoreMethods = {
getFederatedDispatch: typeof getFederatedDispatch
listFederatedDispatchesByIds: typeof listFederatedDispatchesByIds
@@ -133,6 +188,8 @@ export type FederatedDispatchStoreMethods = {
isFederatedDispatchRelayEligible: typeof isFederatedDispatchRelayEligible
updateFederatedDispatchResources: typeof updateFederatedDispatchResources
updateFederatedDispatchRuntimeEpoch: typeof updateFederatedDispatchRuntimeEpoch
setFederatedHomeImportSequence: typeof setFederatedHomeImportSequence
recordFederatedHomeAcknowledgment: typeof recordFederatedHomeAcknowledgment
}
export function attachFederatedDispatchStore(ctor: { prototype: object }): void {
@@ -143,6 +200,8 @@ export function attachFederatedDispatchStore(ctor: { prototype: object }): void
findNextTerminalFederatedDispatchPendingAcknowledgment,
isFederatedDispatchRelayEligible,
updateFederatedDispatchResources,
updateFederatedDispatchRuntimeEpoch
updateFederatedDispatchRuntimeEpoch,
setFederatedHomeImportSequence,
recordFederatedHomeAcknowledgment
})
}
@@ -1,7 +1,7 @@
import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection'
import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db'
import type { FederatedDispatchRow } from '../../../../orchestration/db/orchestration-records'
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import { ORCHESTRATION_FLEET_PAGE_MAX } from '../../../../shared/orchestration/fleet/orchestration-fleet-projection'
import type { OrchestrationDb } from '../db/orchestration-db'
import type { FederatedDispatchRow } from '../db/orchestration-records'
import type { OrcaRuntimeService } from '../../orca-runtime'
type HostGroup = {
environmentId: string
@@ -1,18 +1,18 @@
import { groupFederatedDispatches } from './federated-fleet-host-groups'
import { mapWithConcurrency } from '../../../../../../shared/map-with-concurrency'
import { ORCHESTRATION_FEDERATION_FLEET_SNAPSHOT_RUNTIME_CAPABILITY } from '../../../../../../shared/orchestration/orchestration-runtime-capabilities'
import { mapWithConcurrency } from '../../../../shared/map-with-concurrency'
import { ORCHESTRATION_FEDERATION_FLEET_SNAPSHOT_RUNTIME_CAPABILITY } from '../../../../shared/orchestration/orchestration-runtime-capabilities'
import {
refreshOrchestrationFleetLivenessAttention,
type FleetDurableWorker,
type OrchestrationFleetPage
} from '../../../../../../shared/orchestration/fleet/orchestration-fleet-projection'
import { projectFleetNextAction } from '../../../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection'
import { getOrchestrationPeerCapabilityCache } from '../../../../orchestration/federation/orchestration-peer-capability-cache'
import { liveFederatedHomeAutoReleaseAt } from '../../../../orchestration/terminal-authority/release/worker-terminal-ownership'
import type { OrchestrationDb } from '../../../../orchestration/db/orchestration-db'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import { resolvePinnedFederatedServer } from '../worker/pinned-federated-server'
} from '../../../../shared/orchestration/fleet/orchestration-fleet-projection'
import { projectFleetNextAction } from '../../../../shared/orchestration/fleet/orchestration-fleet-worker-projection'
import { getOrchestrationPeerCapabilityCache } from '../federation/orchestration-peer-capability-cache'
import { liveFederatedHomeAutoReleaseAt } from '../terminal-authority/release/worker-terminal-ownership'
import type { OrchestrationDb } from '../db/orchestration-db'
import { OrchestrationError } from '../orchestration-error'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { resolvePinnedFederatedServer } from '../../rpc/methods/orchestration/worker/pinned-federated-server'
import { applyConfirmedFederatedReleaseHomeProjection } from './federated-worker-release'
const FLEET_HOST_CONCURRENCY = 4
@@ -0,0 +1,85 @@
import type { OrchestrationDb } from '../db/orchestration-db'
import { toSqliteUtcTimestamp } from '../db/utc-timestamp'
import { WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS } from '../db/worker-terminal/worker-terminal-auto-release'
/** Only for a host that cannot release on its own; arms once, so a retain or release before settlement still wins. */
export function armFederatedHomeAutoRelease(
this: OrchestrationDb,
dispatchId: string,
nowMs = Date.now()
): void {
const { changes } = this.db
.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = ?, home_auto_release_state = 'armed', updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state IS NULL`
)
.run(toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS), dispatchId)
if (changes > 0) {
this.workerTerminalAutoReleaseListener?.()
}
}
/** A retain, an explicit release or the host's answer to an attempt ends the home deadline for good. */
export function endFederatedHomeAutoRelease(this: OrchestrationDb, dispatchId: string): void {
this.db
.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = NULL, home_auto_release_state = 'ended', updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state IS NOT 'ended'`
)
.run(dispatchId)
}
/** Claiming postpones the deadline instead of hiding it, so an attempt cut short by a crash or failure runs again. */
export function claimDueFederatedHomeAutoReleases(this: OrchestrationDb, nowMs: number): string[] {
if (this.workerAutoReleaseEnabled?.() === false) {
return []
}
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the SELECT names exactly this one column.
const due = this.db
.prepare(
`SELECT dispatch_id FROM federated_dispatches
WHERE home_auto_release_state = 'armed' AND home_auto_release_at <= ?`
)
.all(toSqliteUtcTimestamp(nowMs)) as { dispatch_id: string }[]
const claim = this.db.prepare(
`UPDATE federated_dispatches
SET home_auto_release_at = ?, updated_at = datetime('now')
WHERE dispatch_id = ? AND home_auto_release_state = 'armed' AND home_auto_release_at <= ?`
)
const retryAt = toSqliteUtcTimestamp(nowMs + WORKER_TERMINAL_AUTO_RELEASE_GRACE_MS)
return due.flatMap(({ dispatch_id }) =>
claim.run(retryAt, dispatch_id, toSqliteUtcTimestamp(nowMs)).changes > 0 ? [dispatch_id] : []
)
}
export function isFederatedHomeAutoReleaseArmed(
this: OrchestrationDb,
dispatchId: string
): boolean {
return (
this.db
.prepare(
`SELECT 1 FROM federated_dispatches
WHERE dispatch_id = ? AND home_auto_release_state = 'armed'`
)
.get(dispatchId) !== undefined
)
}
export type FederatedHomeAutoReleaseStoreMethods = {
armFederatedHomeAutoRelease: typeof armFederatedHomeAutoRelease
endFederatedHomeAutoRelease: typeof endFederatedHomeAutoRelease
claimDueFederatedHomeAutoReleases: typeof claimDueFederatedHomeAutoReleases
isFederatedHomeAutoReleaseArmed: typeof isFederatedHomeAutoReleaseArmed
}
export function attachFederatedHomeAutoReleaseStore(ctor: { prototype: object }): void {
Object.assign(ctor.prototype, {
armFederatedHomeAutoRelease,
endFederatedHomeAutoRelease,
claimDueFederatedHomeAutoReleases,
isFederatedHomeAutoReleaseArmed
})
}
@@ -1,11 +1,11 @@
import type { OrcaRuntimeService } from '../../../../orca-runtime'
import type { OrchestrationSessionCaller } from '../../../../orchestration/addressing/orchestration-caller-identity'
import { OrchestrationError } from '../../../../orchestration/orchestration-error'
import { readCallerStoreInstallationId } from '../../../../hosts/platform-probe/host-descriptor'
import { getCanonicalUserDataPath } from '../../../../../persistence/loading-store/user-data-path'
import type { CrossStoreParentRef } from '../../../../../../shared/worktree/lineage-types'
import { supportsCrossStoreLineage } from '../../../../../../shared/worktree-runtime-capabilities'
import { resolveDispatchCallerWorktreeId } from '../orchestration-caller-workspace'
import type { OrcaRuntimeService } from '../../orca-runtime'
import type { OrchestrationSessionCaller } from '../addressing/orchestration-caller-identity'
import { OrchestrationError } from '../orchestration-error'
import { readCallerStoreInstallationId } from '../../hosts/platform-probe/host-descriptor'
import { getCanonicalUserDataPath } from '../../../persistence/loading-store/user-data-path'
import type { CrossStoreParentRef } from '../../../../shared/worktree/lineage-types'
import { supportsCrossStoreLineage } from '../../../../shared/worktree-runtime-capabilities'
import { resolveDispatchCallerWorktreeId } from '../../rpc/methods/orchestration/orchestration-caller-workspace'
/**
* `--on <server> --worktree new-child`: the server's new worktree nests under the coordinator's

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