- {children}
+
+ {overlay}
+
+ {children}
+
)
}
diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx
index f9c1a56020a..ac46e8db302 100644
--- a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx
+++ b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.test.tsx
@@ -26,13 +26,22 @@ const clear = (sequence: number): AgentJournalRenderItem => ({
})
function render(epoch: string | null, items: AgentJournalRenderItem[]) {
- return renderHook(
+ let restore = (): void => {}
+ const hook = renderHook(
({ epoch, items }) => {
- const { rows, clearing, clears } = useNativeChatContextClearFloor(epoch, items)
- return { shown: rows.map((row) => row.sequence), clearing, clears }
+ const { rows, clearing, clears, onClearSent } = useNativeChatContextClearFloor(epoch, items)
+ return { view: { shown: rows.map((row) => row.sequence), clearing, clears }, onClearSent }
},
{ initialProps: { epoch, items } }
)
+ return {
+ rerender: hook.rerender,
+ get view() {
+ return hook.result.current.view
+ },
+ sendClear: () => act(() => void (restore = hook.result.current.onClearSent())),
+ refuseClear: () => act(() => restore())
+ }
}
describe('useNativeChatContextClearFloor', () => {
@@ -41,24 +50,55 @@ describe('useNativeChatContextClearFloor', () => {
it('fades a live /clear out before the transcript moves to its divider', () => {
const hook = render('epoch-a', [message(1), message(2)])
- expect(hook.result.current).toEqual({ shown: [1, 2], clearing: false, clears: 0 })
+ expect(hook.view).toEqual({ shown: [1, 2], clearing: false, clears: 0 })
hook.rerender({ epoch: 'epoch-a', items: [message(1), message(2), clear(3)] })
- expect(hook.result.current).toEqual({ shown: [1, 2, 3], clearing: true, clears: 0 })
+ expect(hook.view).toEqual({ shown: [1, 2, 3], clearing: true, clears: 0 })
act(() => vi.advanceTimersByTime(NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS))
- expect(hook.result.current).toEqual({ shown: [3], clearing: false, clears: 1 })
+ expect(hook.view).toEqual({ shown: [3], clearing: false, clears: 1 })
+ })
+
+ it('hides the transcript from the moment a /clear is sent until its divider lands', () => {
+ const hook = render('epoch-a', [message(1), message(2)])
+ hook.sendClear()
+ expect(hook.view).toEqual({ shown: [1, 2], clearing: true, clears: 0 })
+
+ // Already faded out by the time the divider lands, so it swaps without a second fade.
+ act(() => vi.advanceTimersByTime(NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS))
+ hook.rerender({ epoch: 'epoch-a', items: [message(1), message(2), clear(3)] })
+ act(() => vi.advanceTimersByTime(0))
+ expect(hook.view).toEqual({ shown: [3], clearing: false, clears: 1 })
+
+ // The answered press hides nothing once later history trims its divider out.
+ hook.rerender({ epoch: 'epoch-a', items: [message(4), message(5)] })
+ expect(hook.view.clearing).toBe(false)
+ })
+
+ it('shows the transcript again when a sent /clear is refused', () => {
+ const hook = render('epoch-a', [message(1), message(2)])
+ hook.sendClear()
+ expect(hook.view.clearing).toBe(true)
+ hook.refuseClear()
+ expect(hook.view).toEqual({ shown: [1, 2], clearing: false, clears: 0 })
+ })
+
+ it('stops hiding once a snapshot past the divider holds none of the rows the press hid', () => {
+ const hook = render('epoch-a', [message(1), message(2)])
+ hook.sendClear()
+ hook.rerender({ epoch: 'epoch-a', items: [message(9), message(10)] })
+ expect(hook.view).toEqual({ shown: [9, 10], clearing: false, clears: 0 })
})
it('moves to a divider paged in from history without fading or replacing the list', () => {
const hook = render('epoch-a', [message(40), message(41)])
hook.rerender({ epoch: 'epoch-a', items: [message(10), clear(11), message(40), message(41)] })
- expect(hook.result.current).toEqual({ shown: [11, 40, 41], clearing: false, clears: 0 })
+ expect(hook.view).toEqual({ shown: [11, 40, 41], clearing: false, clears: 0 })
})
it('takes the divider a first read or a rewind loads without fading', () => {
const hook = render(null, [])
hook.rerender({ epoch: 'epoch-a', items: [message(1), clear(2), message(3)] })
- expect(hook.result.current).toEqual({ shown: [2, 3], clearing: false, clears: 0 })
+ expect(hook.view).toEqual({ shown: [2, 3], clearing: false, clears: 0 })
})
})
diff --git a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts
index 6e883a84420..f4a0ee3e3e4 100644
--- a/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts
+++ b/src/renderer/src/components/native-chat/conversation/projection/use-native-chat-context-clear-floor.ts
@@ -1,6 +1,7 @@
-import { useEffect, useMemo, useRef, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import type { AgentJournalRenderItem } from '../../../../../../shared/agent-session/journal/agent-session-journal-types'
import {
+ agentSessionContextClearOutstanding,
agentSessionTranscriptRows,
latestAgentSessionContextClearSequence
} from '../../../../../../shared/agent-session/agent-session-context-clear'
@@ -14,21 +15,34 @@ type ClearFloorState = {
floor: number
/** A clear that landed live, waiting for the old transcript to fade out. */
fading: number | null
+ /** When the fade that `fading` waits on began, if this view's press began it. */
+ fadedSince: number | null
/** Bumped per live clear; keys the list so nothing the cleared transcript held carries over. */
clears: number
+ /** This view's /clear awaiting its divider: its press time and the newest row drawn then. */
+ sent: { at: number; tail: number } | null
}
-/** Show history after the latest clear; fade live clears before swapping, but preserve scroll for historical dividers. */
+/** Show history after the latest clear; fade live clears before swapping, but preserve scroll for historical dividers.
+ * A sent /clear fades the transcript at once: the host stops the old agent before its divider lands. */
export function useNativeChatContextClearFloor(
epoch: string | null,
items: readonly AgentJournalRenderItem[]
-): { rows: readonly AgentJournalRenderItem[]; clearing: boolean; clears: number } {
+): {
+ rows: readonly AgentJournalRenderItem[]
+ clearing: boolean
+ clears: number
+ /** Call as this view's /clear goes out; the returned restore shows the transcript again if refused. */
+ onClearSent: () => () => void
+} {
const latest = useMemo(() => latestAgentSessionContextClearSequence(items), [items])
const [state, setState] = useState
(() => ({
epoch,
floor: latest,
fading: null,
- clears: 0
+ fadedSince: null,
+ clears: 0,
+ sent: null
}))
// The newest row the last commit drew: a divider past it arrived live, not from an older page.
const tail = items.at(-1)?.sequence ?? 0
@@ -36,36 +50,62 @@ export function useNativeChatContextClearFloor(
useEffect(() => {
drawnTail.current = tail
}, [tail])
+ const onClearSent = useCallback(() => {
+ const sent = { at: Date.now(), tail: drawnTail.current }
+ setState((prior) => ({ ...prior, sent }))
+ return () => setState((prior) => (prior.sent === sent ? { ...prior, sent: null } : prior))
+ }, [])
let current = state
if (epoch !== state.epoch) {
- // A new journal (first read or a rewind) remounts the list on its own; nothing to fade.
- current = { ...state, epoch, floor: latest, fading: null }
+ // A new journal (first read or a rewind) remounts the list on its own; nothing to fade or wait on.
+ current = { ...state, epoch, floor: latest, fading: null, fadedSince: null, sent: null }
setState(current)
} else if (latest > (state.fading ?? state.floor)) {
+ // A divider past the press answers it, so the press stops hiding anything.
+ const { sent } = state
+ const answered = sent !== null && latest > sent.tail
+ const waiting = answered ? null : sent
current =
- latest > drawnTail.current ? { ...state, fading: latest } : { ...state, floor: latest }
+ latest > drawnTail.current
+ ? { ...state, fading: latest, fadedSince: answered ? sent.at : null, sent: waiting }
+ : { ...state, floor: latest, sent: waiting }
+ setState(current)
+ } else if (
+ state.sent !== null &&
+ !agentSessionContextClearOutstanding(items, latest, state.sent.tail)
+ ) {
+ // No row the press hid is loaded any more (a snapshot past its divider).
+ current = { ...state, sent: null }
setState(current)
}
- const fading = current.fading
+ const { fading, fadedSince } = current
+ // Held hidden until a divider newer than the press lands; a refused clear fades back in.
+ const awaitingDivider = agentSessionContextClearOutstanding(
+ items,
+ latest,
+ current.sent?.tail ?? null
+ )
useEffect(() => {
if (fading === null) {
return
}
+ // A press that already faded the transcript out swaps as soon as its divider lands.
+ const elapsed = fadedSince === null ? 0 : Date.now() - fadedSince
const timer = setTimeout(
() =>
setState((prior) =>
prior.fading === fading
- ? { ...prior, floor: fading, fading: null, clears: prior.clears + 1 }
+ ? { ...prior, floor: fading, fading: null, fadedSince: null, clears: prior.clears + 1 }
: prior
),
- NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS
+ Math.max(0, NATIVE_CHAT_CONTEXT_CLEAR_FADE_MS - elapsed)
)
return () => clearTimeout(timer)
- }, [fading])
+ }, [fadedSince, fading])
const floor = current.floor
const rows = useMemo(() => agentSessionTranscriptRows(items, floor), [floor, items])
- return { rows, clearing: fading !== null, clears: current.clears }
+ return { rows, clearing: fading !== null || awaitingDivider, clears: current.clears, onClearSent }
}
diff --git a/src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.ts b/src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.ts
index 352e8cf64b9..6ab811b914e 100644
--- a/src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.ts
+++ b/src/renderer/src/components/native-chat/session/structured/use-structured-agent-session.ts
@@ -248,6 +248,7 @@ export function useStructuredAgentSession(args: StructuredAgentSessionViewArgs)
rewindInFlight: rewind.blockedRef,
sends: pending,
items: () => stateRef.current.items,
+ onClearSent: contextClear.onClearSent,
send: commandWrite
}),
journalItems: transcriptItems,
diff --git a/src/renderer/src/components/native-chat/session/structured/writes/structured-conversation-command-send.ts b/src/renderer/src/components/native-chat/session/structured/writes/structured-conversation-command-send.ts
index 1fd31b30b80..32b424b24f6 100644
--- a/src/renderer/src/components/native-chat/session/structured/writes/structured-conversation-command-send.ts
+++ b/src/renderer/src/components/native-chat/session/structured/writes/structured-conversation-command-send.ts
@@ -40,6 +40,8 @@ export async function sendStructuredConversationCommand(input: {
causes: StructuredConversationCommandCauses
/** What the chat's loaded start-failure rows state, read when the reply lands. */
startFailures: () => readonly AgentSessionFailureFact[]
+ /** Called as a /clear goes out; the returned restore runs unless the host accepts it. */
+ onClearSent?: () => () => void
send: (
command: AgentSessionConversationCommand
) => Promise>
@@ -70,6 +72,8 @@ export async function sendStructuredConversationCommand(input: {
)
}
input.pending.current = true
+ const restoreClear = input.command === 'clear' ? input.onClearSent?.() : undefined
+ let accepted = false
try {
const outcome = await input.send(input.command)
if (outcome.kind === 'not-done') {
@@ -84,9 +88,13 @@ export async function sendStructuredConversationCommand(input: {
startFailures: input.startFailures(),
say: sayAgentSessionFailureTranslated
})
+ accepted = reply.accepted
return reply.accepted ? { accepted: true, error: null } : refused(reply.error, reply.cause)
} finally {
input.pending.current = false
+ if (!accepted) {
+ restoreClear?.()
+ }
}
}
@@ -109,6 +117,7 @@ export function structuredConversationCommandRunner(args: {
sends: readonly StructuredAgentSessionPendingSend[]
/** The loaded rows, read when the reply lands, for the start failures they state. */
items: () => readonly AgentJournalRenderItem[]
+ onClearSent?: () => () => void
send: (
command: AgentSessionConversationCommand,
delivery?: 'queue-if-active',
@@ -152,6 +161,7 @@ export function structuredConversationCommandRunner(args: {
}),
causes,
startFailures: () => agentSessionVisibleFailureFacts(args.items()),
+ onClearSent: args.onClearSent,
send: (command) =>
args.send(
command,
diff --git a/src/shared/agent-session/agent-session-context-clear.ts b/src/shared/agent-session/agent-session-context-clear.ts
index 1a2ad24ddcb..4794f7ac51c 100644
--- a/src/shared/agent-session/agent-session-context-clear.ts
+++ b/src/shared/agent-session/agent-session-context-clear.ts
@@ -49,6 +49,18 @@ export function latestAgentSessionContextClearSequence(
return sequence
}
+/** A /clear sent while `sentTail` was the newest row drawn hides the rows up to it until a divider past it lands.
+ * Once none of those rows is loaded (a tail snapshot past the divider), nothing is left to hide. */
+export function agentSessionContextClearOutstanding(
+ items: readonly Pick[],
+ latestClear: number,
+ sentTail: number | null
+): sentTail is number {
+ return (
+ sentTail !== null && latestClear <= sentTail && (items[0]?.sequence ?? Infinity) <= sentTail
+ )
+}
+
/** Show rows from the /clear divider onward; retain earlier journal rows for workers and archives. */
export function agentSessionTranscriptRows<
T extends Pick
From 5ad35ad5e5df9b072c0b04ac24cfad0c1a7ce27c Mon Sep 17 00:00:00 2001
From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
Date: Sun, 8 Nov 2026 17:37:53 -0800
Subject: [PATCH 03/31] perf(terminal): index sleeping-record and launch-agent
tabs once per parking pass (#40009)
goneSessionsKeepTabMounted scanned every sleeping record per eligible tab,
so a workspace switch with thousands of tabs did tabs x records work on the
renderer thread. Build both owner sets once per source identity instead.
---
.../parked-tab-agent-owner-index.ts | 44 +++++++++++++++++++
.../terminal-parked-tab-watchers.ts | 7 ++-
2 files changed, 47 insertions(+), 4 deletions(-)
create mode 100644 src/renderer/src/components/terminal-pane/parking/output-watchers/parked-tab-agent-owner-index.ts
diff --git a/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-tab-agent-owner-index.ts b/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-tab-agent-owner-index.ts
new file mode 100644
index 00000000000..57f9f976d00
--- /dev/null
+++ b/src/renderer/src/components/terminal-pane/parking/output-watchers/parked-tab-agent-owner-index.ts
@@ -0,0 +1,44 @@
+/** Agent-owner tab sets for gone-session parking, built once per source identity so a pass over every tab stays linear. */
+import type { TerminalTab } from '../../../../../../shared/workspace-layout/terminal-tab-types'
+import type { SleepingAgentSessionRecord } from '../../../../../../shared/agent-session/lifecycle/agent-session-resume'
+
+const launchAgentTabIdsByTabs = new WeakMap>()
+const NO_TAB_IDS: ReadonlySet = new Set()
+
+export function launchAgentTabIds(tabs: readonly TerminalTab[] | undefined): ReadonlySet {
+ if (!tabs) {
+ return NO_TAB_IDS
+ }
+ let tabIds = launchAgentTabIdsByTabs.get(tabs)
+ if (!tabIds) {
+ tabIds = new Set(tabs.flatMap((tab) => (tab.launchAgent ? [tab.id] : [])))
+ launchAgentTabIdsByTabs.set(tabs, tabIds)
+ }
+ return tabIds
+}
+
+let sleepingRecordTabIdsCache: {
+ records: Record
+ tabIds: ReadonlySet
+} | null = null
+
+/** Tabs a sleeping record names by tabId or by a `${tabId}:` pane-key prefix. */
+export function sleepingRecordTabIds(
+ records: Record
+): ReadonlySet {
+ if (sleepingRecordTabIdsCache?.records === records) {
+ return sleepingRecordTabIdsCache.tabIds
+ }
+ const tabIds = new Set()
+ for (const paneKey in records) {
+ const recordTabId = records[paneKey]?.tabId
+ if (recordTabId !== undefined) {
+ tabIds.add(recordTabId)
+ }
+ for (let colon = paneKey.indexOf(':'); colon !== -1; colon = paneKey.indexOf(':', colon + 1)) {
+ tabIds.add(paneKey.slice(0, colon))
+ }
+ }
+ sleepingRecordTabIdsCache = { records, tabIds }
+ return tabIds
+}
diff --git a/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.ts b/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.ts
index 5703e61e4f2..2c6c05ac509 100644
--- a/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.ts
+++ b/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-tab-watchers.ts
@@ -16,6 +16,7 @@ import {
resolveParkedTerminalPaneCandidates,
type ParkableTerminalTabModel
} from './terminal-parked-watcher-reconciliation'
+import { launchAgentTabIds, sleepingRecordTabIds } from './parked-tab-agent-owner-index'
import { collapseParkedExitedLeaf, startParkedPtyWatcher } from './terminal-parked-pty-watcher'
import {
capturedPanesByTabId,
@@ -84,10 +85,8 @@ function goneSessionsKeepTabMounted(
}
return (
goneCount < panes.length ||
- state.tabsByWorktree[worktreeId]?.some((t) => t.id === tab.id && t.launchAgent) === true ||
- Object.entries(state.sleepingAgentSessionsByPaneKey).some(
- ([paneKey, record]) => record.tabId === tab.id || paneKey.startsWith(`${tab.id}:`)
- )
+ launchAgentTabIds(state.tabsByWorktree[worktreeId]).has(tab.id) ||
+ sleepingRecordTabIds(state.sleepingAgentSessionsByPaneKey).has(tab.id)
)
}
From 8bf5e95249047c60144d56d84d69551f33424ec8 Mon Sep 17 00:00:00 2001
From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
Date: Sun, 8 Nov 2026 17:38:25 -0800
Subject: [PATCH 04/31] perf(terminal): group park-exempt sleeping records once
per map; index captured panes by leaf (#40014)
* perf(terminal): group park-exempt sleeping records once per map; index captured panes by leaf
Each mounted worktree's exemption selector rescanned every sleeping record
after a record-map change (worktrees x records), and pane reconciliation
compared every captured pane against every fallback pane (panes^2 per tab).
* perf(terminal): skip the pane index on empty fallbacks; reuse the accumulating leaf traversal
---
.../layout/terminal-layout-leaf-traversal.ts | 12 +---
.../terminal-parked-watcher-reconciliation.ts | 36 ++++++++--
.../sleeping-record-park-exemption.ts | 67 ++++++++++++-------
3 files changed, 73 insertions(+), 42 deletions(-)
diff --git a/src/renderer/src/components/terminal-pane/layout/terminal-layout-leaf-traversal.ts b/src/renderer/src/components/terminal-pane/layout/terminal-layout-leaf-traversal.ts
index 7613e116e64..dd41bd6e2de 100644
--- a/src/renderer/src/components/terminal-pane/layout/terminal-layout-leaf-traversal.ts
+++ b/src/renderer/src/components/terminal-pane/layout/terminal-layout-leaf-traversal.ts
@@ -1,14 +1,8 @@
import type { TerminalPaneLayoutNode } from '../../../../../shared/workspace-layout/terminal-tab-types'
+import { collectLayoutLeafIdsInOrder } from '../../../../../shared/workspace-layout/terminal-pane-tree'
-export function collectLeafIdsInOrder(node: TerminalPaneLayoutNode | null | undefined): string[] {
- if (!node) {
- return []
- }
- if (node.type === 'leaf') {
- return [node.leafId]
- }
- return [...collectLeafIdsInOrder(node.first), ...collectLeafIdsInOrder(node.second)]
-}
+// Accumulate instead of spreading per split, which copies quadratically on skewed layouts.
+export const collectLeafIdsInOrder = collectLayoutLeafIdsInOrder
export function getLeftmostLeafId(node: TerminalPaneLayoutNode): string {
return node.type === 'leaf' ? node.leafId : getLeftmostLeafId(node.first)
diff --git a/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.ts b/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.ts
index 5ffb2b35cff..5b761dcff8e 100644
--- a/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.ts
+++ b/src/renderer/src/components/terminal-pane/parking/output-watchers/terminal-parked-watcher-reconciliation.ts
@@ -38,28 +38,50 @@ export function fallbackParkedPaneCandidates(
}))
}
+function leafPtyKey(leafId: string, ptyId: string | null): string {
+ return `${leafId}\u0000${ptyId ?? ''}\u0000${ptyId === null ? 0 : 1}`
+}
+
+// Index captured panes so a many-split tab stays linear in its pane count.
+function capturedCoversFallback(
+ captured: readonly ParkedTerminalPaneCapture[],
+ fallback: readonly ParkedTerminalPaneCapture[]
+): boolean {
+ const capturedLeafPtyKeys = new Set(
+ captured.map((candidate) => leafPtyKey(candidate.leafId, candidate.ptyId))
+ )
+ return fallback.every((pane) => capturedLeafPtyKeys.has(leafPtyKey(pane.leafId, pane.ptyId)))
+}
+
export function resolveParkedTerminalPaneCandidates(
tab: ParkableTerminalTabModel,
state: ParkedPaneFallbackState
): ParkedTerminalPaneCapture[] {
const captured = capturedPanesByTabId.get(tab.id)
const fallback = fallbackParkedPaneCandidates(tab, state)
+ if (!captured) {
+ return fallback
+ }
const capturedIsCurrent =
- captured !== undefined &&
captured.panes.length > 0 &&
(tab.ptyId === null || captured.panes.some((pane) => pane.ptyId === tab.ptyId)) &&
(fallback.length === 0 ||
(captured.panes.length === fallback.length &&
- fallback.every((pane) =>
- captured.panes.some(
- (candidate) => candidate.leafId === pane.leafId && candidate.ptyId === pane.ptyId
- )
- )))
+ capturedCoversFallback(captured.panes, fallback)))
if (capturedIsCurrent) {
return captured.panes
}
+ if (fallback.length === 0) {
+ return fallback
+ }
+ const priorByLeafId = new Map()
+ for (const candidate of captured.panes) {
+ if (!priorByLeafId.has(candidate.leafId)) {
+ priorByLeafId.set(candidate.leafId, candidate)
+ }
+ }
return fallback.map((pane) => {
- const prior = captured?.panes.find((candidate) => candidate.leafId === pane.leafId)
+ const prior = priorByLeafId.get(pane.leafId)
return prior
? {
...pane,
diff --git a/src/renderer/src/components/terminal-pane/parking/retention/sleeping-record-park-exemption.ts b/src/renderer/src/components/terminal-pane/parking/retention/sleeping-record-park-exemption.ts
index 5039efbd75e..6894156d452 100644
--- a/src/renderer/src/components/terminal-pane/parking/retention/sleeping-record-park-exemption.ts
+++ b/src/renderer/src/components/terminal-pane/parking/retention/sleeping-record-park-exemption.ts
@@ -12,36 +12,51 @@ type SleepingRecordParkExemptionState = {
sleepingAgentSessionsByPaneKey?: Record
}
-/** Exempt only consumable sleeping records: parked panes cannot cold-restore, but finished notes would pin panes forever. Memoize by record-map identity to avoid rescanning every worktree on unrelated writes; iterate without allocating Object.values. */
+let exemptTabIdsByWorktreeCache: {
+ records: Record
+ byWorktreeId: ReadonlyMap>
+} | null = null
+
+/** Group consumable records by worktree once per record map; each mounted worktree then reads its bucket instead of rescanning every record. */
+function exemptTabIdsByWorktree(
+ records: Record
+): ReadonlyMap> {
+ if (exemptTabIdsByWorktreeCache?.records === records) {
+ return exemptTabIdsByWorktreeCache.byWorktreeId
+ }
+ const byWorktreeId = new Map>()
+ for (const paneKey in records) {
+ const record = records[paneKey]
+ if (!record || activationTreatsNoteAsFinished(record)) {
+ continue
+ }
+ // Why: malformed pane keys must yield no owner instead of a truncated tab id.
+ const tabId =
+ record.tabId ??
+ parsePaneKey(record.paneKey)?.tabId ??
+ parseLegacyNumericPaneKey(record.paneKey)?.tabId
+ if (tabId) {
+ let owned = byWorktreeId.get(record.worktreeId)
+ if (!owned) {
+ owned = new Set()
+ byWorktreeId.set(record.worktreeId, owned)
+ }
+ owned.add(tabId)
+ }
+ }
+ exemptTabIdsByWorktreeCache = { records, byWorktreeId }
+ return byWorktreeId
+}
+
+/** Exempt only consumable sleeping records: parked panes cannot cold-restore, but finished notes would pin panes forever. Memoize by record-map identity to avoid rescanning every worktree on unrelated writes. */
export const selectSleepingRecordParkExemptTabIds = createWorktreeRecordSelector<
SleepingRecordParkExemptionState,
ReadonlySet
>({
readSources: (state) => [state.sleepingAgentSessionsByPaneKey],
empty: EMPTY_TAB_IDS,
- build: ({ sleepingAgentSessionsByPaneKey }, worktreeId) => {
- if (!sleepingAgentSessionsByPaneKey) {
- return EMPTY_TAB_IDS
- }
- let owned: Set | null = null
- for (const paneKey in sleepingAgentSessionsByPaneKey) {
- const record = sleepingAgentSessionsByPaneKey[paneKey]
- if (!record || record.worktreeId !== worktreeId) {
- continue
- }
- if (activationTreatsNoteAsFinished(record)) {
- continue
- }
- // Why: malformed pane keys must yield no owner instead of a truncated tab id.
- const tabId =
- record.tabId ??
- parsePaneKey(record.paneKey)?.tabId ??
- parseLegacyNumericPaneKey(record.paneKey)?.tabId
- if (tabId) {
- owned ??= new Set()
- owned.add(tabId)
- }
- }
- return owned ?? EMPTY_TAB_IDS
- }
+ build: ({ sleepingAgentSessionsByPaneKey }, worktreeId) =>
+ sleepingAgentSessionsByPaneKey
+ ? (exemptTabIdsByWorktree(sleepingAgentSessionsByPaneKey).get(worktreeId) ?? EMPTY_TAB_IDS)
+ : EMPTY_TAB_IDS
})
From c192f04dba23807d8efaa6393bfc9235f26a1c02 Mon Sep 17 00:00:00 2001
From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
Date: Sun, 8 Nov 2026 17:44:46 -0800
Subject: [PATCH 05/31] chore(claude): update the Claude Agent SDK to 0.3.318
(#39940)
* chore(claude): update the Claude Agent SDK to 0.3.318
Includes the upstream fix for omitted permissionMode (claude-agent-sdk-typescript#519), so the 'use my Claude settings' permission choice honors settings defaultMode.
* test(orcad): expect the SDK's joined --permission-prompt-tool=stdio argument
Claude Agent SDK 0.3.295+ passes named option values in the same argument as their flag.
* refactor(claude): drop the permission flag SDK 0.3.318 no longer reads
The SDK leaves an omitted permissionMode to the CLI, so the 'own' choice needs no opt-in option.
---
package.json | 2 +-
pnpm-lock.yaml | 12 ++++++------
.../launch/claude-structured-launch-resolution.ts | 8 +++-----
...rcad-packaged-structured-chat.integration.test.ts | 3 +--
4 files changed, 11 insertions(+), 14 deletions(-)
diff --git a/package.json b/package.json
index 4014ada5610..604f23dd467 100644
--- a/package.json
+++ b/package.json
@@ -232,7 +232,7 @@
"check:import-boundaries": "bun config/scripts/static-analysis/process-boundaries/check-import-boundaries.mjs"
},
"dependencies": {
- "@anthropic-ai/claude-agent-sdk": "0.3.284",
+ "@anthropic-ai/claude-agent-sdk": "0.3.318",
"@floating-ui/dom": "1.8.0",
"@linear/sdk": "^97.0.0",
"@orca/process-host": "workspace:*",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a2e0691a065..228db2cb82d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -227,8 +227,8 @@ importers:
.:
dependencies:
'@anthropic-ai/claude-agent-sdk':
- specifier: 0.3.284
- version: 0.3.284(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)
+ specifier: 0.3.318
+ version: 0.3.318(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)
'@floating-ui/dom':
specifier: 1.8.0
version: 1.8.0
@@ -763,9 +763,9 @@ packages:
'@antfu/install-pkg@1.1.0':
resolution: {integrity: sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ==}
- '@anthropic-ai/claude-agent-sdk@0.3.284':
- resolution: {integrity: sha512-NSoJwEq6nFSf8dtaacYx37QdGgqApI3eHFUlxclMLYi8irb6ZJwEaUnPnLUCyAyg9W/tMkgZC0GXWLRCc01I0w==}
- engines: {node: '>=18.0.0'}
+ '@anthropic-ai/claude-agent-sdk@0.3.318':
+ resolution: {integrity: sha512-z5WHCUeW52SKQ3rnvI3zt8X5h2QQ5o3Cgg5xarO5Rimfe67f3pOJt2aOh00S8t/nRzqfs+8nCb9o1EoXe+yccA==}
+ engines: {node: '>=18.14.0'}
peerDependencies:
'@anthropic-ai/sdk': '>=0.93.0'
'@modelcontextprotocol/sdk': ^1.29.0
@@ -8342,7 +8342,7 @@ snapshots:
package-manager-detector: 1.6.0
tinyexec: 1.1.2
- '@anthropic-ai/claude-agent-sdk@0.3.284(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)':
+ '@anthropic-ai/claude-agent-sdk@0.3.318(@anthropic-ai/sdk@0.122.0(zod@4.6.7))(@modelcontextprotocol/sdk@1.32.1(supports-color@7.2.0)(zod@4.6.7))(zod@4.6.7)':
dependencies:
'@anthropic-ai/sdk': 0.122.0(zod@4.6.7)
'@modelcontextprotocol/sdk': 1.32.1(supports-color@7.2.0)(zod@4.6.7)
diff --git a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts
index 096321a9716..e462e89a305 100644
--- a/src/main/claude/structured/launch/claude-structured-launch-resolution.ts
+++ b/src/main/claude/structured/launch/claude-structured-launch-resolution.ts
@@ -55,9 +55,7 @@ export function withClaudeArtifactDefault(
return chosen ? env : { ...env, [CLAUDE_ARTIFACT_ENV]: '1' }
}
-type ClaudePermissionOptions = Pick & {
- resolvePermissionModeInCli?: true
-}
+type ClaudePermissionOptions = Pick
export type ClaudeStructuredSdkOptions = Pick<
ClaudeAgentSdkOptions,
@@ -100,8 +98,8 @@ export function claudeStructuredPermissionOptions(
mode: AgentChatPermissionChoice
): ClaudePermissionOptions {
if (mode === 'own') {
- // upstream request: https://github.com/anthropics/claude-agent-sdk-typescript/issues/519
- return { resolvePermissionModeInCli: true }
+ // An omitted mode lets the CLI apply the user's settings defaultMode.
+ return {}
}
return mode === 'full-access'
? { extraArgs: { 'dangerously-skip-permissions': null } }
diff --git a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts b/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts
index 65ad62692d8..3fe20170630 100644
--- a/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts
+++ b/src/main/orcad/orcad-packaged-structured-chat.integration.test.ts
@@ -326,8 +326,7 @@ describe.skipIf(skip || process.platform === 'win32')('packaged plain-Node struc
'--output-format',
'--include-partial-messages',
'--replay-user-messages',
- '--permission-prompt-tool',
- 'stdio',
+ '--permission-prompt-tool=stdio',
`--session-id=${claudeSessionIdForOrcaSession(sessionId)}`,
'--setting-sources=user,project,local',
'--dangerously-skip-permissions'
From b27c91012891fa52ba919b94dc345a47bd65f3f6 Mon Sep 17 00:00:00 2001
From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com>
Date: Sun, 8 Nov 2026 17:44:59 -0800
Subject: [PATCH 06/31] fix(codex): recognize the 16 app-server notifications
added through Codex 0.167 (#39943)
* fix(codex): recognize the 16 app-server notifications added through Codex 0.167
Users run their own Codex, so 0.167 frames already reach Orca. Unlisted notifications fell back to visible raw rows in the chat timeline; classify each one from the 0.167.0 schema instead.
* test(codex): journal no row for app-server notifications that carry provider text
---
.../codex-app-server-notification-schema.ts | 18 +++++++++++++++++-
...ctured-journal-translation-streams.test.ts | 19 +++++++++++++++++++
.../providers/provider-frame-disposition.ts | 16 ++++++++++++++++
3 files changed, 52 insertions(+), 1 deletion(-)
diff --git a/src/main/codex/app-server/codex-app-server-notification-schema.ts b/src/main/codex/app-server/codex-app-server-notification-schema.ts
index a7319273cdb..4c84ff59b71 100644
--- a/src/main/codex/app-server/codex-app-server-notification-schema.ts
+++ b/src/main/codex/app-server/codex-app-server-notification-schema.ts
@@ -1,16 +1,24 @@
-// Stable ServerNotification method discriminators generated by codex-cli 0.147.0.
+// Stable ServerNotification method discriminators generated by codex-cli 0.167.0.
export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [
'error',
'thread/started',
'thread/status/changed',
+ 'thread/readState/changed',
'thread/archived',
'thread/deleted',
'thread/unarchived',
'thread/closed',
+ 'thread/reverted',
'skills/changed',
'thread/name/updated',
+ 'thread/section/changed',
+ 'thread/attachment/updated',
'thread/goal/updated',
+ 'thread/prediction/updated',
'thread/goal/cleared',
+ 'thread/queue/changed',
+ 'project/changed',
+ 'thread/project/updated',
'thread/environment/connected',
'thread/environment/disconnected',
'thread/settings/updated',
@@ -24,6 +32,7 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [
'item/started',
'item/autoApprovalReview/started',
'item/autoApprovalReview/completed',
+ 'autoApprovalReview/strictReviewRequired',
'item/completed',
'rawResponseItem/completed',
'rawResponse/completed',
@@ -40,7 +49,9 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [
'item/mcpToolCall/progress',
'mcpServer/oauthLogin/completed',
'mcpServer/startupStatus/updated',
+ 'mcpServer/event/stream/notification',
'account/updated',
+ 'account/gatewayOAuth/changed',
'account/rateLimits/updated',
'app/list/updated',
'remoteControl/status/changed',
@@ -53,6 +64,8 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [
'thread/compacted',
'model/rerouted',
'model/verification',
+ 'modelProvider/authRecoveryStarted',
+ 'modelProvider/authRecoveryCompleted',
'turn/moderationMetadata',
'model/safetyBuffering/updated',
'warning',
@@ -63,6 +76,9 @@ export const CODEX_APP_SERVER_NOTIFICATION_METHODS = [
'fuzzyFileSearch/sessionCompleted',
'thread/realtime/started',
'thread/realtime/itemAdded',
+ 'thread/realtime/item/started',
+ 'thread/realtime/item/transcript/delta',
+ 'thread/realtime/item/completed',
'thread/realtime/transcript/delta',
'thread/realtime/transcript/done',
'thread/realtime/outputAudio/delta',
diff --git a/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts b/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts
index 67df104b1d1..74ed29258d7 100644
--- a/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts
+++ b/src/main/codex/structured/journal/codex-structured-journal-translation-streams.test.ts
@@ -198,6 +198,25 @@ describe('codex journal translation', () => {
expect(tap.rows.filter((row) => row.key.includes('provider-frame-suppressed'))).toHaveLength(1)
})
+ it('journals no row for app-server notifications that carry provider text', () => {
+ const { translator, tap, window } = translatorWith()
+
+ translator.handle(TURN_STARTED)
+ translator.handle(
+ notification('thread/prediction/updated', { threadId: THREAD_ID, text: 'Predicted reply' })
+ )
+ translator.handle(
+ notification('modelProvider/authRecoveryStarted', { message: 'Reconnecting to provider' })
+ )
+ translator.handle(
+ notification('modelProvider/authRecoveryCompleted', { message: 'Reconnected' })
+ )
+ translator.handle(notification('account/gatewayOAuth/changed', { error: 'Sign-in expired' }))
+ window.fire()
+
+ expect(tap.rows.filter((row) => row.body.kind === 'status')).toEqual([])
+ })
+
it('writes nothing more after dispose', () => {
const { translator, tap, window } = translatorWith()
diff --git a/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts b/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts
index 85bb374034c..cc31e15d12d 100644
--- a/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts
+++ b/src/main/native-chat/agent-session-wire/providers/provider-frame-disposition.ts
@@ -24,8 +24,16 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = {
'thread/deleted': 'status-chrome',
'thread/unarchived': 'status-chrome',
'thread/closed': 'status-chrome',
+ 'thread/readState/changed': 'suppressed-benign',
+ 'thread/reverted': 'status-chrome',
'skills/changed': 'status-chrome',
'thread/name/updated': 'status-chrome',
+ 'thread/section/changed': 'suppressed-benign',
+ 'thread/attachment/updated': 'status-chrome',
+ 'thread/prediction/updated': 'suppressed-benign',
+ 'thread/queue/changed': 'status-chrome',
+ 'project/changed': 'suppressed-benign',
+ 'thread/project/updated': 'suppressed-benign',
// Goal frames are the only authoritative evidence because goal calls are never emitted as items.
'thread/goal/updated': 'timeline-substantive',
'thread/goal/cleared': 'timeline-substantive',
@@ -43,6 +51,7 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = {
'item/started': 'timeline-substantive',
'item/autoApprovalReview/started': 'status-chrome',
'item/autoApprovalReview/completed': 'status-chrome',
+ 'autoApprovalReview/strictReviewRequired': 'status-chrome',
'item/completed': 'timeline-substantive',
'rawResponseItem/completed': 'suppressed-benign',
'rawResponse/completed': 'suppressed-benign',
@@ -59,7 +68,9 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = {
'item/mcpToolCall/progress': 'status-chrome',
'mcpServer/oauthLogin/completed': 'status-chrome',
'mcpServer/startupStatus/updated': 'status-chrome',
+ 'mcpServer/event/stream/notification': 'suppressed-benign',
'account/updated': 'status-chrome',
+ 'account/gatewayOAuth/changed': 'status-chrome',
'account/rateLimits/updated': 'suppressed-benign',
'app/list/updated': 'status-chrome',
'remoteControl/status/changed': 'status-chrome',
@@ -72,6 +83,8 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = {
'thread/compacted': 'timeline-substantive',
'model/rerouted': 'status-chrome',
'model/verification': 'status-chrome',
+ 'modelProvider/authRecoveryStarted': 'status-chrome',
+ 'modelProvider/authRecoveryCompleted': 'status-chrome',
'turn/moderationMetadata': 'suppressed-benign',
'model/safetyBuffering/updated': 'status-chrome',
warning: 'error-surface',
@@ -82,6 +95,9 @@ export const PROVIDER_FRAME_CLASSIFICATIONS = {
'fuzzyFileSearch/sessionCompleted': 'suppressed-benign',
'thread/realtime/started': 'status-chrome',
'thread/realtime/itemAdded': 'timeline-substantive',
+ 'thread/realtime/item/started': 'status-chrome',
+ 'thread/realtime/item/transcript/delta': 'stream-into-item',
+ 'thread/realtime/item/completed': 'timeline-substantive',
'thread/realtime/transcript/delta': 'stream-into-item',
'thread/realtime/transcript/done': 'timeline-substantive',
'thread/realtime/outputAudio/delta': 'stream-into-item',
From 7d5e5dc2acabb6a8c4a32a3cda9a014e3677fdc6 Mon Sep 17 00:00:00 2001
From: OrcaWin
Date: Sun, 8 Nov 2026 17:47:32 -0800
Subject: [PATCH 07/31] test: remove low-value custom smoke workflows and stale
benchmark (#40060)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
---
.github/workflows/pr.yml | 6 -
config/audit-tools/README.md | 1 -
config/path-literal-baseline.txt | 1 -
.../audit-tools/verify-locked-audit-tools.mjs | 118 ----
.../session-search-file-id-e2e/README.md | 80 ---
.../session-search-file-id-e2e/client.cjs | 30 -
.../session-search-file-id-e2e/host.cjs | 325 ---------
.../scripts/session-search-file-id-e2e/run.ts | 194 ------
.../session-search-file-id-e2e/verify.cjs | 62 --
package.json | 1 -
.../worktree-deletion-branch-fixture.mjs | 69 --
.../worktree-deletion-dev-bench.mjs | 631 ------------------
.../worktree-deletion-timing-samples.mjs | 21 -
.../omp-child-history-rendered/README.md | 5 -
.../tools/omp-child-session-resume-smoke.mjs | 82 ---
.../tools/omp-child-session-runtime-smoke.mjs | 146 ----
.../tools/omp-fresh-session-runtime-smoke.mjs | 75 ---
tests/tools/omp-history-title-smoke.mjs | 92 ---
.../omp-resume-transcript-locator-smoke.mjs | 81 ---
.../tools/omp-session-root-upstream-smoke.mjs | 86 ---
.../omp-source-control-runtime-smoke.mjs | 33 -
tests/tools/omp-source-control-ui/README.md | 4 -
tests/tools/omp-startup-keyboard-smoke.mjs | 99 ---
.../omp-status-input-redaction-smoke.mjs | 101 ---
tests/tools/pi-ui-prompt-cdp-smoke.mjs | 61 --
tests/tools/pi-ui-prompt-extension.mjs | 43 --
tests/tools/pi-ui-prompt-runtime-smoke.mjs | 155 -----
tests/tools/pi-ui-prompt-verification.md | 42 --
28 files changed, 2644 deletions(-)
delete mode 100644 config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
delete mode 100644 config/scripts/session-search-file-id-e2e/README.md
delete mode 100644 config/scripts/session-search-file-id-e2e/client.cjs
delete mode 100644 config/scripts/session-search-file-id-e2e/host.cjs
delete mode 100644 config/scripts/session-search-file-id-e2e/run.ts
delete mode 100644 config/scripts/session-search-file-id-e2e/verify.cjs
delete mode 100644 tests/tools/benchmarks/worktree-deletion-branch-fixture.mjs
delete mode 100644 tests/tools/benchmarks/worktree-deletion-dev-bench.mjs
delete mode 100644 tests/tools/benchmarks/worktree-deletion-timing-samples.mjs
delete mode 100644 tests/tools/omp-child-session-resume-smoke.mjs
delete mode 100644 tests/tools/omp-child-session-runtime-smoke.mjs
delete mode 100644 tests/tools/omp-fresh-session-runtime-smoke.mjs
delete mode 100644 tests/tools/omp-history-title-smoke.mjs
delete mode 100644 tests/tools/omp-resume-transcript-locator-smoke.mjs
delete mode 100644 tests/tools/omp-session-root-upstream-smoke.mjs
delete mode 100644 tests/tools/omp-source-control-runtime-smoke.mjs
delete mode 100644 tests/tools/omp-startup-keyboard-smoke.mjs
delete mode 100644 tests/tools/omp-status-input-redaction-smoke.mjs
delete mode 100644 tests/tools/pi-ui-prompt-cdp-smoke.mjs
delete mode 100644 tests/tools/pi-ui-prompt-extension.mjs
delete mode 100644 tests/tools/pi-ui-prompt-runtime-smoke.mjs
delete mode 100644 tests/tools/pi-ui-prompt-verification.md
diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml
index edc22bc6505..c88dc0f782f 100644
--- a/.github/workflows/pr.yml
+++ b/.github/workflows/pr.yml
@@ -342,12 +342,6 @@ jobs:
if [ "$PREFLIGHT_PHASE_SELECTED" != true ] || [ "$PREFLIGHT_PRIOR_SUCCESS" != true ]; then exit 0; fi
node config/scripts/preflight/changed-checks/check-changed-code-quality.mjs "${{ github.event.pull_request.base.sha }}"
- - name: Verify locked audit tools
- if: needs.code_paths.outputs.static_analysis == 'true'
- env:
- ORCA_BACKGROUND_LAUNCH: '1'
- run: node config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
-
- name: Enforce React Doctor on changed lines
if: needs.code_paths.outputs.static_analysis == 'true'
run: node config/scripts/static-analysis/react-doctor/check-react-doctor-changed.mjs "${{ github.event.pull_request.base.sha }}"
diff --git a/config/audit-tools/README.md b/config/audit-tools/README.md
index 7ae8738106c..9c060fa55a2 100644
--- a/config/audit-tools/README.md
+++ b/config/audit-tools/README.md
@@ -13,4 +13,3 @@ To update a tool, change its exact version in this package's manifest, run
`pnpm --dir config/audit-tools install --ignore-scripts`, and review both the manifest
and generated lockfile. The workspace enforces a three-day release delay and
disables install scripts. Keep its package-manager pin aligned with the root.
-Run `node config/scripts/verify-locked-audit-tools.mjs` to exercise both tools.
diff --git a/config/path-literal-baseline.txt b/config/path-literal-baseline.txt
index a0a0ede85ea..3d31a05c9e5 100644
--- a/config/path-literal-baseline.txt
+++ b/config/path-literal-baseline.txt
@@ -6,7 +6,6 @@
config/scripts/performance/session-search/session-search-tool-heavy-corpus.ts src/main/ai-vault/session-transcript-reader.ts
config/scripts/runtime-verification/desktop-transport/run-linux-lid-sleep-assertion-docker.mjs src/main/linux-lid-sleep-assertion.ts
config/scripts/runtime-verification/desktop-transport/run-ssh-staged-upload-reliability.mjs src/main/ssh/ssh-relay-install-namespace.test.ts
-config/scripts/session-search-file-id-e2e/run.ts src/main/ai-vault/session-scanner-service-entry.ts
config/scripts/static-analysis/ratchets/renderer-state/check-layout-writer-ratchets.mjs src/renderer/src/runtime/remote-workspace-frozen/
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/main/runtime/runtime-worktree-agent-
config/scripts/workflow/source-routing/pr-code-change-scope.mjs src/shared/agent-session-mutation-envelope
diff --git a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs b/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
deleted file mode 100644
index 400546950fb..00000000000
--- a/config/scripts/dependency-security/audit-tools/verify-locked-audit-tools.mjs
+++ /dev/null
@@ -1,118 +0,0 @@
-import assert from 'node:assert/strict'
-import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
-import { join, resolve } from 'node:path'
-import { parse } from 'yaml'
-import { runProcessSync } from '@orca/process-host'
-import { auditToolEntry, installAuditTools } from './run-audit-tool.mjs'
-
-const root = resolve(import.meta.dirname, '../../../..')
-const installed = installAuditTools(root)
-assert.equal(installed.code, 0, 'Frozen, script-free audit tool install failed')
-
-const scratch = join(root, 'tmp')
-mkdirSync(scratch, { recursive: true })
-const fixture = mkdtempSync(join(scratch, 'locked audit tools '))
-const toolManifest = JSON.parse(readFileSync(join(root, 'config/audit-tools/package.json'), 'utf8'))
-
-function command(program, args, expectedCode = 0) {
- const result = runProcessSync({ program, args, cwd: fixture, timeoutMs: 60_000 })
- assert.equal(result.timedOut, false, `${program} timed out`)
- assert.equal(result.signal, null, `${program} received ${result.signal}`)
- assert.equal(result.code, expectedCode, `${result.stdout}\n${result.stderr}`)
- return result.stdout
-}
-
-function tool(name, args, expectedCode = 0) {
- return command(process.execPath, [auditToolEntry(name, root), ...args], expectedCode)
-}
-
-function write(file, value) {
- writeFileSync(join(fixture, file), value)
-}
-
-const cleanComponent = 'export default function App() { return }\n'
-const indexKeyComponent =
- 'export default function App() { return {["one"].map((text, index) => {text})}
}\n'
-const doctorArgs = [
- '.',
- '--yes',
- '--no-dead-code',
- '--no-supply-chain',
- '--no-telemetry',
- '--no-cache',
- '--json',
- '--blocking',
- 'warning'
-]
-
-try {
- command('git', ['init', '--quiet'])
- command('git', ['config', 'core.hooksPath', join(fixture, '.git', 'disabled-hooks')])
- command('git', ['config', 'commit.gpgSign', 'false'])
- write(
- 'package.json',
- JSON.stringify({ name: 'locked-audit-smoke', private: true, dependencies: { react: '19.2.8' } })
- )
- write('App.tsx', cleanComponent)
- write('knip.json', JSON.stringify({ entry: ['App.tsx'], project: ['*.tsx'] }))
-
- for (const name of ['react-doctor', 'knip']) {
- assert.equal(tool(name, ['--version']).trim(), toolManifest.dependencies[name])
- }
-
- const clean = JSON.parse(tool('react-doctor', doctorArgs))
- assert.equal(clean.ok, true)
- assert.ok(clean.projects.some((project) => project.analyzedFiles.includes('App.tsx')))
- tool('knip', ['--config', 'knip.json', '--files'])
-
- write('App.tsx', indexKeyComponent)
- command('git', ['add', '.'])
- command('git', [
- '-c',
- 'user.name=Audit tool smoke',
- '-c',
- 'user.email=audit-smoke@example.invalid',
- 'commit',
- '--quiet',
- '-m',
- 'Baseline'
- ])
- write('Changed.tsx', indexKeyComponent.replace('function App', 'function Changed'))
- command('git', ['add', 'Changed.tsx'])
- const changed = JSON.parse(
- tool('react-doctor', [...doctorArgs, '--scope', 'lines', '--base', 'HEAD'], 1)
- )
- assert.ok(changed.diagnostics.some((item) => item.filePath.endsWith('Changed.tsx')))
- assert.ok(changed.diagnostics.every((item) => !item.filePath.endsWith('App.tsx')))
-
- write('Orphan.tsx', 'export const orphan = true\n')
- assert.match(tool('knip', ['--config', 'knip.json', '--files'], 1), /Orphan\.tsx/)
-
- const stale = join(fixture, 'config', 'audit-tools')
- mkdirSync(stale, { recursive: true })
- mkdirSync(join(fixture, 'config', 'patches'), { recursive: true })
- const toolPolicy = parse(
- readFileSync(join(root, 'config/audit-tools/pnpm-workspace.yaml'), 'utf8')
- )
- for (const patch of Object.values(toolPolicy.patchedDependencies ?? {})) {
- copyFileSync(join(root, 'config/audit-tools', patch), join(stale, patch))
- }
- for (const file of ['pnpm-lock.yaml', 'pnpm-workspace.yaml']) {
- copyFileSync(join(root, 'config', 'audit-tools', file), join(stale, file))
- }
- writeFileSync(
- join(stale, 'package.json'),
- JSON.stringify({
- ...toolManifest,
- dependencies: { ...toolManifest.dependencies, knip: '0.0.0' }
- })
- )
- const rejected = installAuditTools(fixture, (spec) => runProcessSync({ ...spec, stdio: 'pipe' }))
- assert.notEqual(rejected.code, 0, 'A stale tool lockfile was accepted')
- assert.match(`${rejected.stdout}\n${rejected.stderr}`, /OUTDATED_LOCKFILE/)
- console.log(
- 'Locked audit tools: real analysis, changed-line filtering, findings and stale-lock rejection passed'
- )
-} finally {
- rmSync(fixture, { recursive: true, force: true })
-}
diff --git a/config/scripts/session-search-file-id-e2e/README.md b/config/scripts/session-search-file-id-e2e/README.md
deleted file mode 100644
index ae1de7fd994..00000000000
--- a/config/scripts/session-search-file-id-e2e/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Windows session-search file-ID integration reproduction
-
-Opt-in Windows/NTFS harness for #20551. Run from the fix workspace root with
-dependencies, the Electron binary, and Git object `9845bef63a6` available.
-Everything generated stays under ignored `notes/search-ipc/`; each run gets fresh
-roots and a profile. No real transcripts, WSL discovery, desktop windows, or user
-profile are used. The synthetic file is recreated until NTFS assigns a real inode
-above `Number.MAX_SAFE_INTEGER`; failure to obtain one fails the test.
-
-```powershell
-$env:ORCA_BACKGROUND_LAUNCH='1'
-pnpm exec esbuild config/scripts/session-search-file-id-e2e/run.ts --bundle --platform=node --format=esm --packages=external --outfile=notes/search-ipc/run.mjs
-node notes/search-ipc/run.mjs red
-# Expected exit 1: initial indexing/query succeeds, subsequent reconciliation fails.
-node notes/search-ipc/run.mjs green
-# Expected exit 0 for both the lifecycle and fresh-host restart phases.
-node config/scripts/session-search-file-id-e2e/verify.cjs
-```
-
-Run red and green sequentially: their build step reuses the exported source tree.
-The verifier checks the expected red failure, green reports, identical oracle
-expressions after formatting normalization, and that exactly the two file-ID
-SELECT source files differ. It does not turn an arbitrary red failure into success.
-
-## Exact topology
-
-The runner exports **LOCAL integration overlay** #20516 head
-`9845bef63a6d0b80ec37af82b5b275287b8e17df` with `git archive`, then bundles the real
-scanner entry and parent modules with esbuild. It does not check out, stage, or
-push overlay sources. Green changes only the two SELECT projections to the CAST
-expressions in #20551; red retains the original projections. CLI #20514 is unused.
-
-An isolated, windowless Electron host installs the production child search
-enablement using fixture settings. The production shared scanner client invokes
-`spawnAiVaultServiceProcess`, which forks Electron with `ELECTRON_RUN_AS_NODE=1`
-and the real `session-scanner-service-entry`. That child owns the production
-instance, indexer, SQLite search engine, and IPC request handling.
-
-Marker queries come from **separate Node client processes over a real Windows
-named pipe**, through production `UnixSocketTransport`, production `RpcDispatcher`
-and `AI_VAULT_METHODS`, then the search registry/service and scanner IPC. Status
-polls and default-off/disabled responses also exercise registered handlers directly.
-An independent read-only SQLite connection verifies active FTS rows and committed
-file metadata against filesystem size/mtime. The transcript-consumer observation
-logs actual replace/append modes without supplying messages or search results.
-
-Labelled fixture seams, identical in both variants:
-
-- Parent root resolution returns the existing `isolatedScanRoots` fixture.
-- `getSettings` supplies the isolated JSON policy; real enablement/settings-change functions apply it.
-- The child's allowlisted environment includes `ORCA_BACKGROUND_LAUNCH=1`.
-- Passive child PID, IPC, stderr, and transcript-read observations are added.
-- The unused default RPC method catalog is excluded; the dispatcher receives the production `AI_VAULT_METHODS` explicitly. Its runtime context supplies only a fixture runtime ID.
-
-## Oracle and evidence
-
-Default-off creates no DB and returns disabled. Enablement indexes the marker;
-two **real default 20-second recent timer cycles** and two explicit full passes
-preserve it. An append becomes searchable; a rename replacement with equal byte
-length and exactly restored mtime removes the old marker and adds the new one.
-The scanner restarts, then a second Electron host opens the same profile/DB and
-queries again. Disablement followed by an append, explicit reconcile, and 21-second
-wait leaves the DB unchanged and the new marker absent.
-
-`red-latest.json` / `green-latest.json` locate each run. Reports contain parent and
-scanner PIDs, executable/Node/Electron versions, IPC events, raw unsafe inode,
-queries, DB metadata, read modes, and scanner exit codes. `*-stages.jsonl` gives
-live progress; `process-*.log` preserves complete output. `comparison.json` records
-the two-source-only comparison. The production scanner shutdown protocol closes
-only recorded children; the runner waits for its own Electron hosts and external
-clients. Profiles/DBs remain as evidence, not running services.
-
-## Boundaries not exercised
-
-This is not a packaged/full Orca desktop launch. The host and scanner are bundled
-from production sources by this harness, not electron-vite's complete app build.
-The actual runtime authentication/metadata server, CLI routing, remote SSH/relay
-transport, and UI are not exercised. Named-pipe framing and dispatcher are real,
-but the harness connects them directly with a fixture token; it makes no claim
-about production authentication. No session-search UI exists in this topology.
diff --git a/config/scripts/session-search-file-id-e2e/client.cjs b/config/scripts/session-search-file-id-e2e/client.cjs
deleted file mode 100644
index 1922547f6ac..00000000000
--- a/config/scripts/session-search-file-id-e2e/client.cjs
+++ /dev/null
@@ -1,30 +0,0 @@
-const { connect } = require('node:net')
-const assert = require('node:assert/strict')
-assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
-const socket = connect(process.argv[2])
-let buffer = ''
-socket.setEncoding('utf8')
-socket.setTimeout(10_000, () => socket.destroy(new Error('RPC client timeout')))
-socket.on('connect', () =>
- socket.write(
- `${JSON.stringify({
- id: 'file-id-query',
- authToken: 'isolated-fixture',
- method: 'aiVault.searchSessions',
- params: JSON.parse(process.argv[3])
- })}\n`
- )
-)
-socket.on('data', (chunk) => {
- buffer += String(chunk)
- const newline = buffer.indexOf('\n')
- if (newline === -1) {
- return
- }
- console.log(JSON.stringify({ pid: process.pid, response: JSON.parse(buffer.slice(0, newline)) }))
- socket.end()
-})
-socket.on('error', (error) => {
- console.error(error)
- process.exitCode = 1
-})
diff --git a/config/scripts/session-search-file-id-e2e/host.cjs b/config/scripts/session-search-file-id-e2e/host.cjs
deleted file mode 100644
index 17ddbb21ff8..00000000000
--- a/config/scripts/session-search-file-id-e2e/host.cjs
+++ /dev/null
@@ -1,325 +0,0 @@
-const { app } = require('electron')
-const assert = require('node:assert/strict')
-const fs = require('node:fs/promises')
-const { existsSync, appendFileSync } = require('node:fs')
-const { join } = require('node:path')
-const { DatabaseSync } = require('node:sqlite')
-const output = process.argv[2]
-const phase = process.argv[3]
-const profile = join(output, 'profile')
-app.setPath('userData', profile)
-app.setPath('sessionData', join(profile, 'chromium'))
-app.disableHardwareAcceleration()
-globalThis.__fileIdChildren = []
-const report = {
- phase,
- pid: process.pid,
- execPath: process.execPath,
- versions: process.versions,
- stages: [],
- children: [],
- stderr: [],
- ipc: []
-}
-globalThis.__fileIdObserveChild = (child) => {
- globalThis.__fileIdChildren.push(child)
- child.stderr.on('data', (chunk) => report.stderr.push(String(chunk)))
- child.on('message', (message) =>
- report.ipc.push({ pid: child.pid, type: message.type, operation: message.operation })
- )
-}
-const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
-const sessionId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'
-const markers = {
- initial: 'quartzinitialmarker',
- append: 'cobaltappendedmarker',
- replacement: 'velvetreplacedmarker',
- disabled: 'tungstendisabledmarker'
-}
-let api
-let registration
-let transport
-const endpoint = `\\\\.\\pipe\\orca-file-id-${process.pid}`
-let settings = {}
-let transcript
-const database = join(profile, 'ai-vault', 'session-search.sqlite')
-function record(stage, data = {}) {
- const entry = { stage, at: Date.now(), ...data }
- report.stages.push(entry)
- appendFileSync(join(output, `${phase}-stages.jsonl`), `${JSON.stringify(entry)}\n`)
- console.log(stage, JSON.stringify(data))
-}
-function inspect(marker) {
- const db = new DatabaseSync(database, { readOnly: true })
- try {
- const query = db.prepare(
- 'SELECT CAST(ino AS TEXT) AS ino, byte_offset, size_bytes, mtime_ms FROM files WHERE path = ?'
- )
- const rows = db
- .prepare(`SELECT s.session_id FROM messages_fts f JOIN messages m ON m.id=f.rowid
- JOIN sessions s ON s.id=m.session_row_id WHERE messages_fts MATCH ?`)
- .all(marker)
- return { file: query.get(transcript), sessions: rows.map((row) => row.session_id) }
- } finally {
- db.close()
- }
-}
-async function query(marker, present) {
- const result = await api.runProcess({
- program: process.env.ORCA_FILE_ID_NODE,
- args: [
- join(output, 'client.cjs'),
- endpoint,
- JSON.stringify({ query: `"${marker}"`, scope: 'conversation', freshness: 'indexed' })
- ],
- env: process.env,
- timeoutMs: 15_000
- })
- assert.equal(result.code, 0, result.stderr)
- const external = JSON.parse(result.stdout)
- assert.equal(external.response.ok, true, JSON.stringify(external))
- const response = external.response.result
- assert.equal(response.kind, 'results', JSON.stringify(response))
- assert.equal(
- response.hits.some((hit) => hit.sessionId === sessionId),
- present,
- `RPC ${marker}`
- )
- const disk = inspect(marker)
- assert.equal(disk.sessions.includes(sessionId), present, `DB ${marker}`)
- const actual = await fs.stat(transcript)
- assert.equal(
- disk.file.byte_offset,
- actual.size,
- 'Committed cursor covers actual transcript bytes'
- )
- assert.equal(disk.file.size_bytes, actual.size)
- assert.equal(disk.file.mtime_ms, actual.mtimeMs)
- record('query', { marker, present, clientPid: external.pid, endpoint, response, disk })
-}
-async function status() {
- return api.rpc('aiVault.searchStatus', {})
-}
-async function waitFor(predicate, label, timeout = 30_000) {
- const until = Date.now() + timeout
- while (Date.now() < until) {
- const current = await status()
- if (predicate(current)) {
- return current
- }
- await sleep(200)
- }
- throw new Error(`Timed out: ${label}`)
-}
-async function policy(next) {
- const before = settings
- settings = next
- await fs.writeFile(join(profile, 'fixture-settings.json'), JSON.stringify(settings))
- api.applySessionSearchSettingsChange(before, settings)
-}
-async function stopChild() {
- const children = [...globalThis.__fileIdChildren]
- api.resetAiVaultScannerServiceForTests()
- for (const child of children) {
- const until = Date.now() + 5000
- while (child.exitCode === null && child.signalCode === null && Date.now() < until) {
- await sleep(50)
- }
- assert.ok(
- child.exitCode !== null || child.signalCode !== null,
- `Child ${child.pid} did not exit`
- )
- if (!report.children.some((row) => row.pid === child.pid)) {
- report.children.push({
- pid: child.pid,
- spawnfile: child.spawnfile,
- spawnargs: child.spawnargs,
- exitCode: child.exitCode,
- signalCode: child.signalCode
- })
- }
- }
-}
-async function run() {
- assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
- await fs.mkdir(profile, { recursive: true })
- api = require('./production.js')
- api.setAppEnvironment({
- getPath: (name) => (name === 'userData' ? profile : app.getPath(name)),
- getAppPath: () => output,
- getVersion: () => app.getVersion(),
- isPackaged: () => false,
- onWillQuit: (handler) => app.on('will-quit', handler),
- exit: (code) => app.exit(code),
- getAppMetrics: () => app.getAppMetrics()
- })
- const dispatcher = new api.RpcDispatcher({
- methods: api.AI_VAULT_METHODS,
- runtime: { getRuntimeId: () => `file-id-${process.pid}` }
- })
- transport = new api.UnixSocketTransport({ endpoint, kind: 'named-pipe' })
- transport.onMessage((message, reply) => {
- void dispatcher
- .dispatch(JSON.parse(message))
- .then((response) => reply(JSON.stringify(response)))
- })
- await transport.start()
- record('rpc-transport', {
- endpoint,
- auth: 'fixture; production auth/metadata server not booted',
- methods: 'production AI_VAULT_METHODS',
- dispatcher: 'production RpcDispatcher'
- })
- const roots = {
- ...api.isolatedScanRoots(join(output, 'roots')),
- wslHomeDirs: [],
- additionalCodexSessionsDirs: [],
- executionHostId: 'local'
- }
- process.env.ORCA_FILE_ID_ROOTS = JSON.stringify(roots)
- await fs.mkdir(roots.claudeProjectsDir, { recursive: true })
- transcript = join(roots.claudeProjectsDir, `${sessionId}.jsonl`)
- if (phase === 'restart') {
- settings = JSON.parse(await fs.readFile(join(profile, 'fixture-settings.json'), 'utf8'))
- assert.equal(settings.aiVaultSearch.enabled, true)
- const beforeRestart = inspect(markers.replacement)
- registration = api.installChildSessionSearchService({
- dataRoot: profile,
- getSettings: () => settings
- })
- await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'Electron host restart')
- await query(markers.append, false)
- await query(markers.replacement, true)
- assert.deepEqual(inspect(markers.replacement), beforeRestart)
- record('app-host-restart-same-db')
- await disableAndCheck()
- return
- }
- const body = `${api.claudeLines([markers.initial], sessionId, 0).join('\n')}\n`
- await fs.writeFile(transcript, body)
- let raw = await fs.stat(transcript, { bigint: true })
- for (let n = 0; raw.ino <= BigInt(Number.MAX_SAFE_INTEGER) && n < 512; n++) {
- await fs.unlink(transcript)
- await fs.writeFile(transcript, body)
- raw = await fs.stat(transcript, { bigint: true })
- }
- assert.ok(raw.ino > BigInt(Number.MAX_SAFE_INTEGER), 'NTFS must supply an actual unsafe inode')
- record('fixture', {
- transcript,
- rawIno: raw.ino.toString(),
- numericIno: BigInt(Number(raw.ino)).toString()
- })
- registration = api.installChildSessionSearchService({
- dataRoot: profile,
- getSettings: () => settings
- })
- assert.ok(registration)
- assert.equal((await status()).enabled, false)
- assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.initial }), {
- kind: 'unavailable',
- reason: 'disabled'
- })
- assert.equal(existsSync(database), false)
- record('default-off')
- await policy({ aiVaultSearch: { enabled: true, historyDays: null } })
- const initial = await waitFor(
- (s) => s.filesIndexed === 1 && s.phase === 'current',
- 'initial indexing'
- )
- assert.equal(inspect(markers.initial).file.ino, BigInt(Number(raw.ino)).toString())
- await query(markers.initial, true)
- record('initial-indexing', { status: initial })
- let recent = initial
- for (let n = 0; n < 2; n++) {
- const previous = recent
- recent = await waitFor(
- (s) => s.lastReconcileAt > previous.lastReconcileAt,
- 'recent timer reconciliation'
- )
- assert.equal(
- recent.lastSweepCompletedAt,
- initial.lastSweepCompletedAt,
- 'Expected a recent pass'
- )
- await query(markers.initial, true)
- record('recent-pass', { status: recent })
- }
- for (let n = 0; n < 2; n++) {
- await api.reconcileSessionSearchInService()
- await query(markers.initial, true)
- record('full-pass', { status: await status() })
- }
- await fs.appendFile(
- transcript,
- `${api.claudeLines([markers.append], sessionId, 10).join('\n')}\n`
- )
- const frozen = new Date(Math.floor((await fs.stat(transcript)).mtimeMs))
- await fs.utimes(transcript, frozen, frozen)
- await api.reconcileSessionSearchInService()
- await query(markers.append, true)
- const before = await fs.stat(transcript)
- const replacement = `${transcript}.replacement`
- const replacementBody = (await fs.readFile(transcript, 'utf8')).replaceAll(
- markers.append,
- markers.replacement
- )
- assert.equal(Buffer.byteLength(replacementBody), before.size)
- await fs.writeFile(replacement, replacementBody)
- await fs.rename(replacement, transcript)
- await fs.utimes(transcript, before.atime, before.mtime)
- const after = await fs.stat(transcript)
- assert.equal(after.size, before.size)
- assert.equal(after.mtimeMs, before.mtimeMs)
- assert.notEqual(after.ino, before.ino)
- await api.reconcileSessionSearchInService()
- await query(markers.append, false)
- await query(markers.replacement, true)
- record('replacement', { beforeIno: before.ino, afterIno: after.ino })
- await stopChild()
- await waitFor((s) => s.filesIndexed === 1 && s.phase === 'current', 'scanner restart')
- await query(markers.append, false)
- await query(markers.replacement, true)
- record('service-restart')
-}
-async function disableAndCheck() {
- await policy({ aiVaultSearch: { enabled: false, historyDays: null } })
- await waitFor((s) => !s.enabled, 'disable')
- const snapshot = inspect(markers.replacement)
- await fs.appendFile(
- transcript,
- `${api.claudeLines([markers.disabled], sessionId, 20).join('\n')}\n`
- )
- await api.reconcileSessionSearchInService()
- await sleep(21_000)
- assert.deepEqual(await api.rpc('aiVault.searchSessions', { query: markers.disabled }), {
- kind: 'unavailable',
- reason: 'disabled'
- })
- assert.deepEqual(inspect(markers.replacement), snapshot)
- assert.deepEqual(inspect(markers.disabled).sessions, [])
- record('disabled-no-indexing')
-}
-app.whenReady().then(async () => {
- try {
- await run()
- report.ok = true
- } catch (error) {
- report.ok = false
- report.error = error.stack
- console.error(error)
- } finally {
- registration?.dispose()
- await transport?.stop()
- if (api) {
- await stopChild().catch((error) => {
- report.cleanupError = String(error)
- report.ok = false
- })
- }
- if (report.stderr.some((text) => text.includes('[ai-vault-search]'))) {
- report.ok = false
- }
- await fs.writeFile(join(output, `report-${phase}.json`), JSON.stringify(report, null, 2))
- app.exit(report.ok ? 0 : 1)
- }
-})
diff --git a/config/scripts/session-search-file-id-e2e/run.ts b/config/scripts/session-search-file-id-e2e/run.ts
deleted file mode 100644
index 3ab6b5ae15d..00000000000
--- a/config/scripts/session-search-file-id-e2e/run.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import assert from 'node:assert/strict'
-import { mkdir, readFile, writeFile, copyFile } from 'node:fs/promises'
-import { resolve, join, relative } from 'node:path'
-import { createHash } from 'node:crypto'
-import { build } from 'esbuild'
-import { runProcess } from '@orca/process-host'
-
-const root = process.cwd()
-const evidence = resolve('notes/search-ipc')
-const overlay = join(evidence, 'overlay')
-const wiring = '9845bef63a6'
-const mode = process.argv[2]
-assert.equal(process.platform, 'win32', 'This harness requires native Windows and NTFS')
-assert.ok(mode === 'red' || mode === 'green', 'Pass red or green')
-assert.equal(process.env.ORCA_BACKGROUND_LAUNCH, '1')
-const output = join(evidence, mode, String(Date.now()))
-await mkdir(output, { recursive: true })
-
-async function command(program: string, args: string[]) {
- const result = await runProcess({ program, args, cwd: root, timeoutMs: 120_000 })
- assert.equal(result.code, 0, result.stderr)
- return result.stdout.trim()
-}
-
-// The overlay is exported, never checked out or staged on the fix branch.
-await mkdir(overlay, { recursive: true })
-await command('git', [
- 'archive',
- '--format=tar',
- `--output=${join(evidence, 'overlay.tar')}`,
- wiring,
- 'src'
-])
-await command('tar', [
- '-xf',
- relative(root, join(evidence, 'overlay.tar')),
- '-C',
- relative(root, overlay)
-])
-const edits: { path: string; sha256: string }[] = []
-function replaceOnce(source: string, before: string, after: string) {
- assert.equal(source.split(before).length, 2, `Expected exactly one injection: ${before}`)
- return source.replace(before, after)
-}
-
-const adapter = join(output, 'adapter.mjs')
-const source = (path: string) => JSON.stringify(join(overlay, 'src', path))
-await writeFile(
- adapter,
- `
-export { installChildSessionSearchService, applySessionSearchSettingsChange } from ${source('main/ai-vault-search/session-search-enablement.ts')};
-export { resetAiVaultScannerServiceForTests, reconcileSessionSearchInService } from ${source('main/ai-vault/session-scanner-service-spawn.ts')};
-export { setAppEnvironment } from ${source('shared/app-environment.ts')};
-export { isolatedScanRoots } from ${source('main/ai-vault/session-scanner-test-fixtures.ts')};
-export { claudeLines } from ${source('main/ai-vault-search/session-search-indexer-test-fixture.ts')};
-export { runProcess } from '@orca/process-host';
-export { UnixSocketTransport } from ${source('main/runtime/rpc/unix-socket-transport.ts')};
-export { RpcDispatcher } from ${source('main/runtime/rpc/dispatcher.ts')};
-export { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
-import { buildRegistry } from ${source('main/runtime/rpc/core.ts')};
-import { AI_VAULT_METHODS } from ${source('main/runtime/rpc/methods/ai-vault.ts')};
-const registry = buildRegistry(AI_VAULT_METHODS);
-export async function rpc(name, params) {
- const method = registry.get(name);
- if (!method || !name.startsWith('aiVault.search')) throw new Error('Unexpected method');
- return method.handler(method.params.parse(params), {});
-}
-`
-)
-
-await build({
- entryPoints: {
- production: adapter,
- 'session-scanner-service-entry': join(
- overlay,
- 'src/main/ai-vault/session-scanner-service-entry.ts'
- )
- },
- outdir: output,
- platform: 'node',
- format: 'cjs',
- bundle: true,
- packages: 'external',
- define: { ORCA_FEATURE_WALL_ENABLED: 'true' },
- plugins: [
- {
- name: 'labelled-local-fixtures',
- setup(api) {
- api.onLoad({ filter: /\.ts$/ }, async (args) => {
- let contents = await readFile(args.path, 'utf8')
- const path = args.path.replaceAll('\\', '/')
- if (path.endsWith('/runtime/rpc/methods/rpc-method-registry.ts')) {
- // DispatcherOptions explicitly supplies AI_VAULT_METHODS; don't load unrelated default methods.
- contents = 'export const ALL_RPC_METHODS = []'
- }
- if (path.endsWith('/cached-session-list.ts')) {
- contents = replaceOnce(
- contents,
- ' const [additionalCodexHomes, wslHomeDirs] = await Promise.all([',
- ' return JSON.parse(process.env.ORCA_FILE_ID_ROOTS!);\n const [additionalCodexHomes, wslHomeDirs] = await Promise.all(['
- )
- }
- if (path.endsWith('/session-scanner-service-env.ts')) {
- contents = replaceOnce(
- contents,
- " env.ELECTRON_RUN_AS_NODE = '1'",
- " env.ORCA_BACKGROUND_LAUNCH = '1'\n env.ELECTRON_RUN_AS_NODE = '1'"
- )
- }
- if (path.endsWith('/session-scanner-service-spawn.ts')) {
- contents = replaceOnce(
- contents,
- ' lowerAiVaultServicePriority(child.pid)',
- ' globalThis.__fileIdObserveChild?.(child)\n lowerAiVaultServicePriority(child.pid)'
- )
- }
- if (path.endsWith('/session-scanner-service-entry.ts')) {
- contents = `import { registerTranscriptConsumer } from './session-transcript-consumers';
-registerTranscriptConsumer({beginRead: start => { console.error('[file-id-read]', JSON.stringify({mode:start.mode,path:start.candidate.file.path})); return null }});
-console.error('[file-id-child]', JSON.stringify({pid:process.pid,execPath:process.execPath,versions:process.versions,background:process.env.ORCA_BACKGROUND_LAUNCH}));\n${contents}`
- }
- if (mode === 'green' && path.endsWith('/session-search-store.ts')) {
- contents = replaceOnce(
- contents,
- 'SELECT path, dev, ino, mtime_ms',
- 'SELECT path, CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, mtime_ms'
- )
- }
- if (mode === 'green' && path.endsWith('/session-search-index-writer.ts')) {
- contents = replaceOnce(
- contents,
- 'SELECT dev, ino, byte_offset',
- 'SELECT CAST(dev AS REAL) AS dev, CAST(ino AS REAL) AS ino, byte_offset'
- )
- }
- edits.push({
- path: path.replace(overlay.replaceAll('\\', '/'), ''),
- sha256: createHash('sha256').update(contents).digest('hex')
- })
- return { contents, loader: 'ts' }
- })
- }
- }
- ]
-})
-await copyFile(
- join(root, 'config/scripts/session-search-file-id-e2e/host.cjs'),
- join(output, 'host.cjs')
-)
-await copyFile(
- join(root, 'config/scripts/session-search-file-id-e2e/client.cjs'),
- join(output, 'client.cjs')
-)
-await writeFile(
- join(output, 'topology.json'),
- JSON.stringify(
- {
- wiring: await command('git', ['rev-parse', wiring]),
- fix: await command('git', ['rev-parse', 'HEAD']),
- mode,
- injections: [
- 'isolated root resolver',
- 'background child env',
- 'child PID/error/read observation',
- 'unused default RPC catalog excluded; explicit production AI_VAULT_METHODS'
- ],
- files: edits.sort((a, b) => a.path.localeCompare(b.path))
- },
- null,
- 2
- )
-)
-await writeFile(join(evidence, `${mode}-latest.json`), JSON.stringify({ output }))
-for (const phase of ['lifecycle', 'restart']) {
- console.log(JSON.stringify({ mode, phase, output }))
- const result = await runProcess({
- program: join(root, 'node_modules/electron/dist/electron.exe'),
- args: [join(output, 'host.cjs'), output, phase],
- cwd: output,
- env: {
- ...process.env,
- ORCA_BACKGROUND_LAUNCH: '1',
- ELECTRON_RUN_AS_NODE: undefined,
- ORCA_FILE_ID_NODE: process.execPath
- },
- timeoutMs: 180_000
- })
- await writeFile(join(output, `process-${phase}.log`), result.stdout + result.stderr)
- console.log(JSON.stringify({ mode, phase, code: result.code, timedOut: result.timedOut, output }))
- process.exitCode = result.code ?? 1
- if (process.exitCode !== 0) {
- break
- }
-}
diff --git a/config/scripts/session-search-file-id-e2e/verify.cjs b/config/scripts/session-search-file-id-e2e/verify.cjs
deleted file mode 100644
index 180bf4cf154..00000000000
--- a/config/scripts/session-search-file-id-e2e/verify.cjs
+++ /dev/null
@@ -1,62 +0,0 @@
-const assert = require('node:assert/strict')
-const { readFileSync, writeFileSync } = require('node:fs')
-const { join, resolve } = require('node:path')
-const { createHash } = require('node:crypto')
-const { transformSync } = require('esbuild')
-const evidence = resolve('notes/search-ipc')
-const json = (path) => JSON.parse(readFileSync(path, 'utf8'))
-const red = json(join(evidence, 'red-latest.json')).output
-const green = json(join(evidence, 'green-latest.json')).output
-const before = json(join(red, 'topology.json'))
-const after = json(join(green, 'topology.json'))
-assert.equal(before.wiring, after.wiring)
-assert.deepEqual(before.injections, after.injections)
-const oldFiles = new Map(before.files.map((row) => [row.path, row.sha256]))
-assert.equal(oldFiles.size, after.files.length)
-const changed = after.files
- .filter((row) => oldFiles.get(row.path) !== row.sha256)
- .map((row) => row.path)
- .sort()
-assert.deepEqual(changed, [
- '/src/main/ai-vault-search/session-search-index-writer.ts',
- '/src/main/ai-vault-search/session-search-store.ts'
-])
-for (const name of ['host.cjs', 'client.cjs']) {
- // Ignore formatter-only differences; preserve every expression and assertion.
- const hash = (root) =>
- createHash('sha256')
- .update(
- transformSync(readFileSync(join(root, name), 'utf8'), {
- loader: 'js',
- minifyWhitespace: true
- }).code
- )
- .digest('hex')
- assert.equal(hash(red), hash(green), `Identical oracle: ${name}`)
-}
-const failed = json(join(red, 'report-lifecycle.json'))
-assert.equal(failed.ok, false)
-assert.match(failed.stderr.join(''), /RangeError: Value is too large/)
-assert.ok(failed.stages.some((row) => row.stage === 'initial-indexing'))
-const reports = [
- json(join(green, 'report-lifecycle.json')),
- json(join(green, 'report-restart.json'))
-]
-for (const report of reports) {
- assert.equal(report.ok, true)
- assert.ok(report.ipc.some((row) => row.operation === 'searchSessions'))
- assert.ok(report.stages.some((row) => row.stage === 'query' && row.clientPid !== report.pid))
- assert.ok(report.children.every((child) => child.exitCode === 0))
-}
-assert.notEqual(reports[0].pid, reports[1].pid)
-const result = {
- ok: true,
- wiring: before.wiring,
- changed,
- red,
- green,
- parentPids: [failed.pid, ...reports.map((row) => row.pid)],
- childPids: [failed, ...reports].flatMap((report) => report.children.map((child) => child.pid))
-}
-writeFileSync(join(evidence, 'comparison.json'), JSON.stringify(result, null, 2))
-console.log(JSON.stringify(result))
diff --git a/package.json b/package.json
index 604f23dd467..faf04c0f277 100644
--- a/package.json
+++ b/package.json
@@ -207,7 +207,6 @@
"bench:wsl-git-shell": "node config/scripts/performance/wsl-git/wsl-git-shell-benchmark.mjs",
"bench:hang-watchdog-memory": "pnpm run ensure:electron-runtime && node config/scripts/diagnostics/hang-watchdog/hang-watchdog-memory-benchmark.mjs",
"bench:main-thread-jank": "pnpm run ensure:electron-runtime && node tests/tools/benchmarks/main-thread-jank-bench.mjs",
- "bench:worktree-deletion": "node tests/tools/benchmarks/worktree-deletion-dev-bench.mjs",
"bench:zustand-selector-fanout": "node config/scripts/performance/renderer-projection/zustand-selector-fanout-benchmark.mjs",
"bench:agent-inspection-cadence": "node config/scripts/performance/agent-lineage/agent-inspection-cadence-batching-benchmark.mjs",
"bench:renderer-quadratic-scans": "node config/scripts/performance/renderer-markdown/renderer-quadratic-scan-benchmark.mjs",
diff --git a/tests/tools/benchmarks/worktree-deletion-branch-fixture.mjs b/tests/tools/benchmarks/worktree-deletion-branch-fixture.mjs
deleted file mode 100644
index c655e059b5d..00000000000
--- a/tests/tools/benchmarks/worktree-deletion-branch-fixture.mjs
+++ /dev/null
@@ -1,69 +0,0 @@
-import { spawnSync } from 'node:child_process'
-import net from 'node:net'
-import path from 'node:path'
-
-function runGit(args, cwd) {
- const result = spawnSync('git', args, { cwd, encoding: 'utf8' })
- if (result.status !== 0) {
- throw new Error(`git ${args.join(' ')} failed (${result.status})\n${result.stderr}`)
- }
- return result.stdout.trim()
-}
-
-export function initializeBranchCleanupRemote(fixtureRoot, repoPath) {
- const remotePath = path.join(fixtureRoot, 'remote.git')
- runGit(['init', '--bare', remotePath], fixtureRoot)
- runGit(['symbolic-ref', 'HEAD', 'refs/heads/main'], remotePath)
- runGit(['remote', 'add', 'origin', remotePath], repoPath)
- runGit(['push', 'origin', 'main'], repoPath)
-}
-
-export function seedBranchCleanupRepro(repoPath, worktreePath) {
- runGit(
- ['commit', '--allow-empty', '-m', 'Trigger safe branch cleanup', '--no-gpg-sign'],
- worktreePath
- )
- const branch = runGit(['symbolic-ref', '--short', 'HEAD'], worktreePath)
- runGit(['config', `branch.${branch}.base`, 'refs/remotes/origin/main'], repoPath)
-}
-
-export async function startDelayedFetchServer(delayMs) {
- const sockets = new Set()
- const timers = new Set()
- const server = net.createServer((socket) => {
- sockets.add(socket)
- const timer = setTimeout(() => {
- timers.delete(timer)
- socket.end('HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\n\r\n')
- }, delayMs)
- timers.add(timer)
- socket.on('close', () => {
- clearTimeout(timer)
- timers.delete(timer)
- sockets.delete(socket)
- })
- socket.on('error', () => undefined)
- })
- await new Promise((resolve, reject) => {
- server.once('error', reject)
- server.listen(0, '127.0.0.1', resolve)
- })
- const address = server.address()
- if (!address || typeof address === 'string') {
- throw new Error('Delayed fetch server did not expose a TCP port')
- }
- return {
- url: `http://127.0.0.1:${address.port}/remote.git`,
- close: () =>
- new Promise((resolve) => {
- for (const timer of timers) {
- clearTimeout(timer)
- }
- timers.clear()
- for (const socket of sockets) {
- socket.destroy()
- }
- server.close(resolve)
- })
- }
-}
diff --git a/tests/tools/benchmarks/worktree-deletion-dev-bench.mjs b/tests/tools/benchmarks/worktree-deletion-dev-bench.mjs
deleted file mode 100644
index 17ac22e3fe1..00000000000
--- a/tests/tools/benchmarks/worktree-deletion-dev-bench.mjs
+++ /dev/null
@@ -1,631 +0,0 @@
-#!/usr/bin/env node
-/**
- * A/B benchmark for worktree deletion against real Orca dev instances.
- *
- * Usage:
- * pnpm bench:worktree-deletion -- --instance baseline=/path/to/main \
- * --instance candidate=. --iterations 3 --history-files 10000
- */
-import { spawn, spawnSync } from 'node:child_process'
-import { createHash } from 'node:crypto'
-import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
-import { rm } from 'node:fs/promises'
-import net from 'node:net'
-import os from 'node:os'
-import path from 'node:path'
-// Use declared @playwright/test’s re-export instead of relying on a hoisted transitive playwright install.
-import { chromium } from '@playwright/test'
-import * as branchFixture from './worktree-deletion-branch-fixture.mjs'
-import { round, summarize } from './worktree-deletion-timing-samples.mjs'
-
-const DEFAULT_ITERATIONS = 3
-const DEFAULT_HISTORY_FILES = 10_000
-const DEFAULT_FETCH_DELAY_MS = 1_500
-const CDP_START_PORT = 9_700
-const START_TIMEOUT_MS = 180_000
-const IPC_TIMEOUT_MS = 90_000
-const resultsRoot = path.resolve(import.meta.dirname, 'results')
-
-function parseArgs(argv) {
- const options = {
- instances: [],
- iterations: DEFAULT_ITERATIONS,
- historyFiles: DEFAULT_HISTORY_FILES,
- fetchDelayMs: DEFAULT_FETCH_DELAY_MS,
- keepFixture: false
- }
- for (let index = 2; index < argv.length; index += 1) {
- const value = argv[index]
- if (value === '--') {
- continue
- }
- if (value === '--help' || value === '-h') {
- printHelp()
- process.exit(0)
- }
- if (value === '--keep-fixture') {
- options.keepFixture = true
- continue
- }
- const next = () => {
- const result = argv[++index]
- if (!result) {
- throw new Error(`${value} needs a value`)
- }
- return result
- }
- if (value === '--instance') {
- const entry = next()
- const separator = entry.indexOf('=')
- if (separator <= 0) {
- throw new Error('--instance must use label=/absolute/or/relative/path')
- }
- options.instances.push({
- label: entry.slice(0, separator),
- repoRoot: path.resolve(entry.slice(separator + 1))
- })
- } else if (value === '--iterations') {
- options.iterations = readPositiveInteger(value, next())
- } else if (value === '--history-files') {
- options.historyFiles = readPositiveInteger(value, next())
- } else if (value === '--fetch-delay-ms') {
- options.fetchDelayMs = readPositiveInteger(value, next())
- } else {
- throw new Error(`Unknown argument: ${value}`)
- }
- }
- if (options.instances.length === 0) {
- options.instances.push({ label: 'candidate', repoRoot: process.cwd() })
- }
- return options
-}
-
-function readPositiveInteger(flag, value) {
- const number = Number(value)
- if (!Number.isInteger(number) || number < 1) {
- throw new Error(`${flag} must be a positive integer`)
- }
- return number
-}
-
-function printHelp() {
- console.log(`Usage:
- pnpm bench:worktree-deletion -- [options]
-
-Options:
- --instance