fix(ai-vault): support session scanning in SSH worktrees (#11004)

* fix(ai-vault): support session scanning in SSH worktrees

Add relay-native aiVault.listSessions scanning that discovers agent
sessions on SSH hosts. Includes fallback to filesystem crawl for
legacy relays, full cancellation support, result validation, and
scan coalescing to reduce redundant work.

* fix(ai-vault): scan sessions in SSH worktrees with coordinated cancellat

- Extract batching logic to `mapRemoteScanBatches` for reuse and proper cancellation checkpoints
- Move `AiVaultScanCoordinator` from relay to main to handle concurrent same-key requests with individual cancellation signals
- Report scope path truncation consistently across relay and SSH fallback paths
- Gracefully degrade relay handler on unsupported platforms instead of aborting startup
- Refactor issue display to separate blocking errors, scope notices, and skipped transcript counts

* fix(ai-vault): stabilize SSH session scan CI

Swallow async WSL relay stdin EPIPE so the live hook-relay shard no longer
fails after all tests pass. Merge main, resolve scan/relay conflicts, and
align cancellation/host-issue reporting with IPC expectations.

* fix(ai-vault): harden session scan cancellation, relay timeouts, and preemption

Thread the abort signal through every scan and parse path so superseded or
cancelled scans stop promptly instead of parsing every remaining transcript
for a caller that already left.  Replace the fragile message-text relay
timeout check with a typed error code so unrelated errors carrying the
phrase "timed out after" no longer suppress the filesystem fallback.  Fix
scan coordinator preemption so a forced Refresh in one window no longer
re-enters as a spurious cancellation in another.  Add a host-leg cache for
the all-hosts view and cap filesystem concurrency so a single slow remote
home cannot stall the whole merge.

Co-authored-by: Orca <help@stably.ai>

* fix(ai-vault): use stable React keys for scan issue banners

Drop array-index keys so react-doctor/no-array-index-as-key passes.
Uniqueness comes from host, kind, agent, path, and message.

* fix(ai-vault): SSH session scanning with configurable depth limits

Implement depth-aware caching and proper scan boundaries to make SSH session
scanning reliable in worktrees. Users can now select between faster (250
sessions) and comprehensive (unlimited) history scans. The scanner:
- Deduplicates scans across relay, host leg, runtime, and renderer layers
- Reuses larger scans to serve smaller depth requests
- Properly bounds in-scope discovery per-limit
- Fixes timeout enforcement when SSH providers ignore abort signals

* Move sessionLimit ref update to useLayoutEffect

Keep render pure for React Doctor by deferring ref updates to
a layout effect, which still executes before render-dependent
effects that consume the ref.

* fix(adhoc): stamp version prefix from main, not the feature branch

Adhoc builds check out arbitrary refs whose package.json often lags
version bumps (e.g. 1.4.165-rc.0 while main is 1.4.168-rc.1). Hourly
always builds main so it already tracks the product line; adhoc now
resolves the base version from origin/main (or ORCA_ADHOC_BASE_VERSION)
so branch builds share that prefix.

* Revert "fix(adhoc): stamp version prefix from main, not the feature branch"

This reverts commit a26a18eb3fd83f7e7d2db9a6a7c3e02e0f79089a.

* fix(ai-vault): fix scoped backfill and coordinator race conditions

Resolve race where the last waiter leaving could abort an already-settled scan (add `settled` flag). Redesign scoped session backfill to keep searching through newer files until the scope reaches its requested session quota instead of stopping at the candidate limit; out-of-scope files no longer consume the scope budget. Centralize scan limit normalization and fix error classification for cancelled scans using the proper helper instead of checking Error.name. Disambiguate cache keys using JSON and add cancellation check after scope discovery phase.

---------

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Jinjing
2026-08-03 16:17:00 -07:00
committed by GitHub
co-authored by Orca
parent a7282fed40
commit d7fe9d6bcc
86 changed files with 4389 additions and 584 deletions
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it } from 'vitest'
import type { AiVaultListResult, AiVaultSession } from './ai-vault-types'
import {
aiVaultScanLimit,
aiVaultSessionDepthCovers,
requestedAiVaultSessionDepth,
truncateAiVaultListResult
} from './ai-vault-session-depth'
function session(id: string, cwd: string, index: number): AiVaultSession {
const timestamp = new Date(Date.UTC(2026, 7, 2, 0, 0, index)).toISOString()
return {
id,
executionHostId: 'local',
agent: 'codex',
sessionId: id,
title: id,
cwd,
branch: null,
model: null,
filePath: `/sessions/${id}.jsonl`,
codexHome: null,
createdAt: timestamp,
updatedAt: timestamp,
modifiedAt: timestamp,
messageCount: 1,
totalTokens: 0,
previewMessages: [],
queuedMessageCount: 0,
subagentTranscriptCount: 0,
resumeCommand: id,
subagent: null
}
}
function result(sessions: AiVaultSession[]): AiVaultListResult {
return { sessions, issues: [], scannedAt: '2026-08-02T00:00:00.000Z' }
}
describe('Agent Session History depth', () => {
it('recognizes which loaded depths cover a request', () => {
expect(aiVaultSessionDepthCovers(250, 250)).toBe(true)
expect(aiVaultSessionDepthCovers(1000, 250)).toBe(true)
expect(aiVaultSessionDepthCovers(250, 500)).toBe(false)
expect(aiVaultSessionDepthCovers(1000, 'unlimited')).toBe(false)
expect(aiVaultSessionDepthCovers('unlimited', 1000)).toBe(true)
expect(aiVaultSessionDepthCovers('unlimited', 'unlimited')).toBe(true)
})
it('normalizes default, finite, and unlimited requests', () => {
expect(requestedAiVaultSessionDepth()).toBe(1000)
expect(requestedAiVaultSessionDepth({ limit: 500 })).toBe(500)
expect(requestedAiVaultSessionDepth({ limit: 500.75 })).toBe(500)
expect(requestedAiVaultSessionDepth({ limit: 0 })).toBe(1000)
expect(requestedAiVaultSessionDepth({ limit: -1 })).toBe(1000)
expect(requestedAiVaultSessionDepth({ limit: Number.NaN })).toBe(1000)
expect(requestedAiVaultSessionDepth({ limit: Number.POSITIVE_INFINITY })).toBe(1000)
expect(requestedAiVaultSessionDepth({ limit: 500, unlimited: true })).toBe('unlimited')
})
it('resolves scan limits to a numeric bound', () => {
expect(aiVaultScanLimit({ limit: 500 })).toBe(500)
expect(aiVaultScanLimit({ limit: Number.POSITIVE_INFINITY })).toBe(1000)
expect(aiVaultScanLimit({ unlimited: true })).toBe(Number.POSITIVE_INFINITY)
})
it('keeps the newest global and scoped sessions when truncating', () => {
const loaded = result([
session('global-1', '/other', 6),
session('global-2', '/other', 5),
session('global-3', '/other', 4),
session('scoped-1', '/repo/app', 3),
session('scoped-2', '/repo/lib', 2),
session('scoped-3', '/repo/old', 1)
])
expect(truncateAiVaultListResult(loaded, 2, ['/repo']).sessions.map(({ id }) => id)).toEqual([
'global-1',
'global-2',
'scoped-1',
'scoped-2'
])
expect(truncateAiVaultListResult(loaded, 'unlimited')).toBe(loaded)
})
})
+55
View File
@@ -0,0 +1,55 @@
import { isPathInsideOrEqual } from './cross-platform-path'
import type { AiVaultListArgs, AiVaultListResult } from './ai-vault-types'
export const DEFAULT_AI_VAULT_SCAN_LIMIT = 1000
export type AiVaultSessionDepth = number | 'unlimited'
export function requestedAiVaultSessionDepth(
args?: Pick<AiVaultListArgs, 'limit' | 'unlimited'>
): AiVaultSessionDepth {
if (args?.unlimited === true) {
return 'unlimited'
}
return args?.limit && Number.isFinite(args.limit) && args.limit > 0
? Math.floor(args.limit)
: DEFAULT_AI_VAULT_SCAN_LIMIT
}
// Scanners bound with slice/comparisons, so 'unlimited' resolves to no bound.
// Single owner of the normalization every scan limit goes through.
export function aiVaultScanLimit(args?: Pick<AiVaultListArgs, 'limit' | 'unlimited'>): number {
const depth = requestedAiVaultSessionDepth(args)
return depth === 'unlimited' ? Number.POSITIVE_INFINITY : depth
}
export function aiVaultSessionDepthCovers(
cached: AiVaultSessionDepth,
requested: AiVaultSessionDepth
): boolean {
return cached === 'unlimited' || (requested !== 'unlimited' && cached >= requested)
}
export function truncateAiVaultListResult(
result: AiVaultListResult,
depth: AiVaultSessionDepth,
scopePaths: readonly string[] = []
): AiVaultListResult {
if (depth === 'unlimited') {
return result
}
const selectedIds = new Set(result.sessions.slice(0, depth).map((session) => session.id))
if (scopePaths.length > 0) {
let scopedCount = 0
for (const session of result.sessions) {
const cwd = session.cwd
if (cwd && scopePaths.some((scopePath) => isPathInsideOrEqual(scopePath, cwd))) {
selectedIds.add(session.id)
if (++scopedCount >= depth) {
break
}
}
}
}
return { ...result, sessions: result.sessions.filter((session) => selectedIds.has(session.id)) }
}
+17
View File
@@ -25,6 +25,17 @@ export const AI_VAULT_AGENTS = [
// value are optional belt-and-braces, not required for the request to succeed.
export const AI_VAULT_SCOPE_PATHS_MAX_COUNT = 64
// Why: IPC rejection drops `Error.name`, so the renderer can only recognise a
// cancelled scan by its message. Both sides share this literal.
export const AI_VAULT_SCAN_CANCELLED_MESSAGE = 'Agent Session History scan was cancelled'
export function isAiVaultScanCancelledError(error: unknown): boolean {
return (
error instanceof Error &&
(error.name === 'AbortError' || error.message.includes(AI_VAULT_SCAN_CANCELLED_MESSAGE))
)
}
export type AiVaultAgent = (typeof AI_VAULT_AGENTS)[number]
export type AiVaultScope = 'workspace' | 'project' | 'all'
export type AiVaultSort = 'updated' | 'created'
@@ -172,23 +183,29 @@ export function isAiVaultSessionRecoverableEmpty(
export type AiVaultScanIssue = {
executionHostId?: ExecutionHostId
agent: AiVaultAgent
// 'notice' rows are scanner commentary (issue-list overflow), never a failure.
kind?: 'host' | 'scope' | 'notice'
path: string
message: string
}
export type AiVaultListArgs = {
limit?: number
unlimited?: boolean
force?: boolean
// Active workspace/project paths. The global result is recency-capped, so these
// guarantee a scoped view still surfaces its own (possibly older) sessions.
scopePaths?: readonly string[]
executionHostScope?: ExecutionHostScope
requestToken?: string
}
export type AiVaultListResult = {
sessions: AiVaultSession[]
issues: AiVaultScanIssue[]
scannedAt: string
/** Set only by the desktop IPC boundary: this scan was superseded, so its empty body means "nothing to apply". */
cancelled?: true
}
export function aiVaultAgentLabel(agent: AiVaultAgent): string {
+12
View File
@@ -0,0 +1,12 @@
export const SSH_AI_VAULT_LIST_SESSIONS_METHOD = 'aiVault.listSessions' as const
export const SSH_AI_VAULT_LIST_SESSIONS_TIMEOUT_MS = 130_000
export const SSH_AI_VAULT_LIST_LIMIT_MAX = 1000
export const SSH_AI_VAULT_SCOPE_PATH_MAX_LENGTH = 4096
export type SshAiVaultRelayListParams = {
limit?: number
unlimited?: boolean
force?: boolean
scopePaths?: string[]
scopePathsTruncated?: boolean
}