mirror of
https://github.com/stablyai/orca.git
synced 2026-10-03 00:02:19 +00:00
* perf(native-chat): probe WSL transcript paths asynchronously The WSL transcript resolvers probed `\wsl.localhost` UNC candidates with existsSync. Those paths are served over 9P, so a stopped or unreachable distro blocked the Electron main thread instead of falling through to the next candidate. - host-readable-transcript-path: the `pathExists` dep is now async, defaulting to fs/promises.access. The per-distro loop stays sequential — the ranked order exists so the owning distro wins, and probing every distro at once would fan 9P calls out to ones the user deliberately left stopped. - session-file-resolver: dropped the existsSync guard outright rather than converting it. walkSessionFiles already yields [] for a missing or unreadable root, so the guard was redundant as well as blocking. * perf(native-chat): stop the resolve poll mkdir-ing the Codex runtime home codexSessionsDirs() only needs the managed home's path to scan it, but called getOrcaManagedCodexHomePath(), which mkdirSyncs. That put a synchronous fs call back on the 500ms-5s resolve poll the surrounding async probe work just cleared, and materialized the runtime home as a side effect of a read-only lookup. Use the resolve-only variant the module already exposes for this case. A missing root walks to no matches, so behavior is unchanged. * perf(native-chat): gate WSL transcript fs access behind a shared queue Serializes and dedupes WSL 9P filesystem probes (access/readdir) so a stopped or slow distro can't exhaust the shared libuv threadpool or block unrelated local filesystem work. Routes Codex session-tree scans and path-existence checks through the new wsl-transcript-fs-gate, while sharing in-flight scans across concurrent callers. * perf(native-chat): prioritize exact WSL transcript probes over scans - Add cancellation (AbortSignal) throughout session resolution and directory walking so an unsubscribed transcript watch stops in-flight WSL filesystem work instead of leaking it. - Split the WSL fs task gate into exact vs scan priority lanes with per-route concurrency, so a live transcript access probe is never queued behind a directory scan on another distro/provider. - Extract Codex WSL session path scanning into its own module that shares one root snapshot across concurrent session-id lookups and refreshes on a shared miss to see post-start file creation. - Skip the async WSL probe entirely for local paths via existsSync. * fix(native-chat): harden WSL transcript cancellation * fix(native-chat): finish transcript cancellation --------- Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
259 lines
8.2 KiB
TypeScript
259 lines
8.2 KiB
TypeScript
import { open, stat } from 'node:fs/promises'
|
|
import type {
|
|
AgentType,
|
|
NativeChatMessage,
|
|
NativeChatTurnLifecycle
|
|
} from '../../shared/native-chat-types'
|
|
import { resolveNativeChatTranscriptAgent } from '../../shared/native-chat-agent-support'
|
|
import { resolveSessionFilePath, type ResolveSessionFileOptions } from './session-file-resolver'
|
|
import {
|
|
decodeClaudeTranscriptLine,
|
|
decodeCodexTranscriptLine,
|
|
decodeGrokTranscriptLine,
|
|
decodeOmpTranscriptLine
|
|
} from './transcript-line-decoders'
|
|
import { transcriptFallbackId } from './transcript-fallback-id'
|
|
import {
|
|
nativeChatTurnLifecycleDecoderForAgent,
|
|
type NativeChatTurnLifecycleDecoder
|
|
} from './transcript-turn-lifecycle'
|
|
|
|
export const MAX_NATIVE_CHAT_TRANSCRIPT_RECORD_BYTES = 2 * 1024 * 1024
|
|
const TAIL_CHUNK_BYTES = 64 * 1024
|
|
|
|
export type NativeChatLineDecoder = (line: string, fallbackId: string) => NativeChatMessage | null
|
|
|
|
export function nativeChatLineDecoderForAgent(agent: AgentType): NativeChatLineDecoder | null {
|
|
const transcriptAgent = resolveNativeChatTranscriptAgent(agent)
|
|
if (transcriptAgent === 'claude') {
|
|
return decodeClaudeTranscriptLine
|
|
}
|
|
if (transcriptAgent === 'codex') {
|
|
return decodeCodexTranscriptLine
|
|
}
|
|
if (transcriptAgent === 'grok') {
|
|
return decodeGrokTranscriptLine
|
|
}
|
|
if (transcriptAgent === 'omp') {
|
|
return decodeOmpTranscriptLine
|
|
}
|
|
return null
|
|
}
|
|
|
|
export async function readNativeChatTranscriptTailFile(
|
|
filePath: string,
|
|
limit: number,
|
|
decode: NativeChatLineDecoder,
|
|
includeTrailingLine = false,
|
|
endOffset?: number,
|
|
decodeLifecycle?: NativeChatTurnLifecycleDecoder | null
|
|
): Promise<{
|
|
messages: NativeChatMessage[]
|
|
lifecycle?: NativeChatTurnLifecycle
|
|
consumedTo: number
|
|
hasMore: boolean
|
|
beforeOffset: number
|
|
malformedRecordCount?: number
|
|
oversizedRecordCount?: number
|
|
}> {
|
|
const end = Math.min((await stat(filePath)).size, endOffset ?? Number.MAX_SAFE_INTEGER)
|
|
if (end === 0) {
|
|
return { messages: [], consumedTo: 0, hasMore: false, beforeOffset: 0 }
|
|
}
|
|
const handle = await open(filePath, 'r')
|
|
const lineParts: Buffer[] = []
|
|
let lineBytes = 0
|
|
let lineOversized = false
|
|
let lifecycle: NativeChatTurnLifecycle | undefined
|
|
let malformedRecordCount = 0
|
|
let oversizedRecordCount = 0
|
|
let ignoreNextMalformedRecord = false
|
|
try {
|
|
const consumedTo = includeTrailingLine ? end : await findLastCompleteLineEnd(handle, end)
|
|
if (consumedTo === 0) {
|
|
return { messages: [], consumedTo: 0, hasMore: false, beforeOffset: 0 }
|
|
}
|
|
const newestFirst: { message: NativeChatMessage; offset: number }[] = []
|
|
const finalByte = Buffer.allocUnsafe(1)
|
|
await handle.read(finalByte, 0, 1, consumedTo - 1)
|
|
ignoreNextMalformedRecord = finalByte[0] !== 0x0a
|
|
let cursor = consumedTo - (finalByte[0] === 0x0a ? 1 : 0)
|
|
while (cursor > 0 && newestFirst.length <= limit) {
|
|
const start = Math.max(0, cursor - TAIL_CHUNK_BYTES)
|
|
const buffer = Buffer.allocUnsafe(cursor - start)
|
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, start)
|
|
let segmentEnd = bytesRead
|
|
for (let index = bytesRead - 1; index >= 0 && newestFirst.length <= limit; index--) {
|
|
if (buffer[index] !== 0x0a) {
|
|
continue
|
|
}
|
|
retainPart(buffer.subarray(index + 1, segmentEnd))
|
|
if (!lineOversized) {
|
|
decodeLine(start + index + 1, newestFirst)
|
|
}
|
|
resetLine()
|
|
segmentEnd = index
|
|
}
|
|
if (segmentEnd > 0) {
|
|
retainPart(buffer.subarray(0, segmentEnd))
|
|
}
|
|
cursor = start
|
|
}
|
|
if (cursor === 0 && lineParts.length > 0 && newestFirst.length <= limit) {
|
|
decodeLine(0, newestFirst)
|
|
}
|
|
const chronological = newestFirst.toReversed()
|
|
// Why: slice(-0) returns the whole array, so a non-positive limit must
|
|
// window to nothing explicitly rather than leak every buffered record.
|
|
const selected = limit > 0 ? chronological.slice(Math.max(0, chronological.length - limit)) : []
|
|
return {
|
|
messages: selected.map((entry) => entry.message),
|
|
...(lifecycle ? { lifecycle } : {}),
|
|
consumedTo,
|
|
hasMore: limit > 0 && chronological.length > limit,
|
|
beforeOffset: selected[0]?.offset ?? end,
|
|
...(malformedRecordCount > 0 ? { malformedRecordCount } : {}),
|
|
...(oversizedRecordCount > 0 ? { oversizedRecordCount } : {})
|
|
}
|
|
} finally {
|
|
await handle.close()
|
|
}
|
|
|
|
function retainPart(part: Buffer): void {
|
|
if (lineOversized) {
|
|
return
|
|
}
|
|
lineBytes += part.length
|
|
if (lineBytes > MAX_NATIVE_CHAT_TRANSCRIPT_RECORD_BYTES) {
|
|
lineParts.length = 0
|
|
lineOversized = true
|
|
oversizedRecordCount++
|
|
return
|
|
}
|
|
lineParts.push(part)
|
|
}
|
|
|
|
function resetLine(): void {
|
|
lineParts.length = 0
|
|
lineBytes = 0
|
|
lineOversized = false
|
|
}
|
|
|
|
function decodeLine(
|
|
lineOffset: number,
|
|
messages: { message: NativeChatMessage; offset: number }[]
|
|
): void {
|
|
let line = Buffer.concat([...lineParts].toReversed()).toString('utf8')
|
|
if (line.endsWith('\r')) {
|
|
line = line.slice(0, -1)
|
|
}
|
|
if (!line) {
|
|
return
|
|
}
|
|
try {
|
|
JSON.parse(line)
|
|
} catch {
|
|
if (ignoreNextMalformedRecord) {
|
|
ignoreNextMalformedRecord = false
|
|
return
|
|
}
|
|
malformedRecordCount++
|
|
return
|
|
}
|
|
ignoreNextMalformedRecord = false
|
|
const fallbackId = transcriptFallbackId(filePath, lineOffset)
|
|
// Why: scan the same bounded JSONL window for provider-authored lifecycle
|
|
// records so reconnect snapshots can replay completion without guessing
|
|
// from the last visible assistant message.
|
|
lifecycle ??= decodeLifecycle?.(line, fallbackId) ?? undefined
|
|
const message = decode(line, fallbackId)
|
|
if (message) {
|
|
messages.push({ message, offset: lineOffset })
|
|
}
|
|
}
|
|
}
|
|
|
|
async function findLastCompleteLineEnd(
|
|
handle: Awaited<ReturnType<typeof open>>,
|
|
end: number
|
|
): Promise<number> {
|
|
const lastByte = Buffer.allocUnsafe(1)
|
|
await handle.read(lastByte, 0, 1, end - 1)
|
|
if (lastByte[0] === 0x0a) {
|
|
return end
|
|
}
|
|
let cursor = end
|
|
while (cursor > 0) {
|
|
const start = Math.max(0, cursor - TAIL_CHUNK_BYTES)
|
|
const buffer = Buffer.allocUnsafe(cursor - start)
|
|
const { bytesRead } = await handle.read(buffer, 0, buffer.length, start)
|
|
const newline = buffer.subarray(0, bytesRead).lastIndexOf(0x0a)
|
|
if (newline >= 0) {
|
|
return start + newline + 1
|
|
}
|
|
cursor = start
|
|
}
|
|
return 0
|
|
}
|
|
|
|
export async function readNativeChatTranscriptTail(
|
|
args: ResolveSessionFileOptions & {
|
|
agent: AgentType
|
|
sessionId: string
|
|
transcriptPath?: string
|
|
filePath?: string
|
|
limit: number
|
|
beforeOffset?: number
|
|
},
|
|
signal?: AbortSignal
|
|
): Promise<
|
|
| {
|
|
messages: NativeChatMessage[]
|
|
lifecycle?: NativeChatTurnLifecycle
|
|
hasMore: boolean
|
|
beforeOffset: number
|
|
}
|
|
| { error: string; notFound?: true }
|
|
> {
|
|
const decode = nativeChatLineDecoderForAgent(args.agent)
|
|
const decodeLifecycle = nativeChatTurnLifecycleDecoderForAgent(args.agent)
|
|
const filePath =
|
|
args.filePath ?? (await resolveSessionFilePath(args.agent, args.sessionId, args, signal))
|
|
signal?.throwIfAborted()
|
|
if (!decode) {
|
|
return { error: 'Transcript unavailable' }
|
|
}
|
|
// Why: a new agent session can report its id before the first JSONL flush;
|
|
// callers keep that miss in loading/retry rather than showing a false error.
|
|
if (!filePath) {
|
|
return { error: 'Transcript unavailable', notFound: true }
|
|
}
|
|
try {
|
|
const result = await readNativeChatTranscriptTailFile(
|
|
filePath,
|
|
args.limit,
|
|
decode,
|
|
true,
|
|
args.beforeOffset,
|
|
decodeLifecycle
|
|
)
|
|
signal?.throwIfAborted()
|
|
return {
|
|
messages: result.messages,
|
|
// Why: an older pagination page must not rewind the live lifecycle; only
|
|
// the current transcript tail can authoritatively describe turn state.
|
|
...(args.beforeOffset === undefined && result.lifecycle
|
|
? { lifecycle: result.lifecycle }
|
|
: {}),
|
|
hasMore: result.hasMore,
|
|
beforeOffset: result.beforeOffset
|
|
}
|
|
} catch (error) {
|
|
signal?.throwIfAborted()
|
|
const message = error instanceof Error ? error.message : String(error)
|
|
return (error as NodeJS.ErrnoException | null)?.code === 'ENOENT'
|
|
? { error: message, notFound: true }
|
|
: { error: message }
|
|
}
|
|
}
|