Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions mobile/src/session/ai-vault-resume-launch.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import type { AiVaultSession } from '../../../src/shared/ai-vault-types'
import { buildAgentResumeStartupPlan } from '../../../src/shared/tui-agent-startup'
import {
buildMobileAiVaultResumeLaunch,
buildMobileAiVaultResumeCommand,
Expand Down Expand Up @@ -120,6 +121,50 @@ describe('buildMobileAiVaultResumeCommand', () => {
})

describe('buildMobileAiVaultResumeLaunch', () => {
it('preserves an arbitrary OMP transcript locator for later cold resume', () => {
const launch = buildMobileAiVaultResumeLaunch({
session: session({
agent: 'omp',
sessionId: 'omp-custom-1',
filePath: '/custom/omp-sessions/project/session.jsonl'
}),
hostPlatform: 'linux',
settings: {
agentDefaultArgs: { omp: '--model custom' },
agentDefaultEnv: { omp: { OMP_PROFILE: 'custom' } }
}
})

expect(launch).toMatchObject({
command:
"cd '/Users/ada/repo' && omp '--model' 'custom' --resume '/custom/omp-sessions/project/session.jsonl'",
env: { OMP_PROFILE: 'custom' },
launchConfig: {
agentCommand: "omp '--model' 'custom'",
agentArgs: '--model custom',
agentEnv: { OMP_PROFILE: 'custom' },
ompResumeFilePath: '/custom/omp-sessions/project/session.jsonl'
},
launchAgent: 'omp'
})

const coldLaunch = buildAgentResumeStartupPlan({
agent: 'omp',
providerSession: { key: 'session_id', id: 'omp-custom-1' },
cmdOverrides: {},
agentArgs: launch.launchConfig?.agentArgs,
agentEnv: launch.launchConfig?.agentEnv,
agentCommand: launch.launchConfig?.agentCommand,
ompResumeFilePath: launch.launchConfig?.ompResumeFilePath,
platform: 'linux'
})
expect(coldLaunch).toMatchObject({
launchCommand:
"omp '--model' 'custom' '--resume' '/custom/omp-sessions/project/session.jsonl'",
env: { OMP_PROFILE: 'custom' }
})
})

it('uses shared TUI startup planning for default args, env, and launch config', () => {
const launch = buildMobileAiVaultResumeLaunch({
session: session({
Expand Down
34 changes: 25 additions & 9 deletions mobile/src/session/ai-vault-resume-launch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
resolveTuiAgentLaunchArgs,
resolveTuiAgentLaunchEnv
} from '../../../src/shared/tui-agent-launch-defaults'
import { normalizeAiVaultResumeFilePath } from '../../../src/shared/ai-vault-resume-path'
import type { TuiAgent } from '../../../src/shared/types'
import { parseWslUncPath } from '../../../src/shared/wsl-paths'
import { resolveWindowsShellStartupFamily } from '../../../src/shared/windows-terminal-shell'
Expand Down Expand Up @@ -58,7 +59,7 @@ export function buildMobileAiVaultResumeCommand(args: {
sessionId: args.session.sessionId,
// Why: OMP resumes by absolute transcript path (custom OMP dir / WSL-store
// sessions miss on an id lookup), so mobile forwards it like desktop does.
resumeFilePath: args.session.filePath,
resumeFilePath: normalizeAiVaultResumeFilePath(args.session.filePath, args.hostPlatform),
cwd: args.session.cwd,
platform: args.hostPlatform,
commandOverride: args.commandOverride,
Expand Down Expand Up @@ -97,6 +98,7 @@ export function buildMobileAiVaultResumeLaunch(args: {
args.settings?.agentCmdOverrides
)
const commandOverride = cmdOverrides[args.session.agent] ?? null
const resumeFilePath = normalizeAiVaultResumeFilePath(args.session.filePath, args.hostPlatform)
if (isResumableTuiAgent(args.session.agent)) {
const startupPlan = buildAgentResumeStartupPlan({
agent: args.session.agent,
Expand All @@ -105,17 +107,31 @@ export function buildMobileAiVaultResumeLaunch(args: {
platform: args.hostPlatform,
shell,
agentArgs: resolveTuiAgentLaunchArgs(args.session.agent, args.settings?.agentDefaultArgs),
agentEnv: resolveTuiAgentLaunchEnv(args.session.agent, args.settings?.agentDefaultEnv)
agentEnv: resolveTuiAgentLaunchEnv(args.session.agent, args.settings?.agentDefaultEnv),
...(args.session.agent === 'omp' && resumeFilePath
? { ompResumeFilePath: resumeFilePath }
: {})
})
if (startupPlan) {
return {
command: buildAiVaultResumeShellCommand({
resumeCommand: startupPlan.launchCommand,
cwd: args.session.cwd,
platform: args.hostPlatform,
codexHome,
shell
}),
command:
args.session.agent === 'omp'
? buildMobileAiVaultResumeCommand({
session: {
...args.session,
...(resumeFilePath ? { filePath: resumeFilePath } : {})
},
hostPlatform: args.hostPlatform,
hostTerminalWindowsShell: args.hostTerminalWindowsShell,
commandOverride: startupPlan.launchConfig.agentCommand
})
: buildAiVaultResumeShellCommand({
resumeCommand: startupPlan.launchCommand,
cwd: args.session.cwd,
platform: args.hostPlatform,
codexHome,
shell
}),
...(startupPlan.env ? { env: startupPlan.env } : {}),
// Why: the resume command is typed into the created pane, so the bare
// real-home override must strip Codex homes at pane spawn like desktop.
Expand Down
84 changes: 74 additions & 10 deletions src/main/pi/agent-status-extension-source.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -436,20 +436,84 @@ describe('getPiAgentStatusExtensionSource', () => {
)
})

it('routes an OMP executable through /hook/omp', async () => {
const harness = createHarness({
kind: 'pi',
title: 'omp',
existsSync: () => false
})
it('tracks persistent OMP sessions and clears ephemeral session ids', async () => {
const harness = createHarness({ kind: 'omp' })
let sessionId = 'omp-session-8'
const sessionManager = { getSessionId: () => sessionId, getSessionFile: () => '/tmp/s' }

await harness.callHook('agent_start')
await harness.callHook('agent_start', undefined, { sessionManager })
sessionId = 'omp-session-9'
await harness.callHook('before_agent_start', { prompt: 'hi' }, { sessionManager })
await vi.waitFor(() => expect(harness.fetchMock).toHaveBeenCalledTimes(2))
await harness.callHook('agent_end', undefined, {
sessionManager: { getSessionId: () => 'omp-ephemeral' }
})

expect(harness.fetchMock).toHaveBeenCalledTimes(1)
expect(harness.fetchMock.mock.calls[0]?.[0]).toBe('http://127.0.0.1:4321/hook/omp')
expect(harness.spawnMock).not.toHaveBeenCalled()
await vi.waitFor(() => expect(harness.fetchMock).toHaveBeenCalledTimes(3))
expect(
harness.fetchMock.mock.calls.map(([_, init]) => JSON.parse(String(init?.body)).payload)
).toEqual([
{ hook_event_name: 'agent_start', session_id: 'omp-session-8' },
{
hook_event_name: 'before_agent_start',
prompt: 'hi',
session_id: 'omp-session-9'
},
{ hook_event_name: 'agent_end' }
])
})

it.each([
['OMP extension', { kind: 'omp' as const }],
['runtime-routed OMP', { kind: 'pi' as const, title: 'omp' }]
])(
'keeps queued %s status bound to the session active when it was posted',
async (_name, args) => {
const finishDeliveries: (() => void)[] = []
const harness = createHarness({
...args,
fetchImpl: vi.fn(
() =>
new Promise((resolve) => {
finishDeliveries.push(() => resolve({ ok: true }))
})
)
})

await harness.callHook('agent_start', undefined, {
sessionManager: {
getSessionId: () => 'omp-session-8',
getSessionFile: () => '/tmp/omp-session-8.jsonl'
}
})
await harness.callHook(
'message_end',
{ message: { role: 'assistant', content: 'done' } },
{
sessionManager: {
getSessionId: () => 'omp-session-9',
getSessionFile: () => '/tmp/omp-session-9.jsonl'
}
}
)
await harness.callHook('message_end', { message: { role: 'user', content: 'next' } }, {})

finishDeliveries[0]?.()
await vi.waitFor(() => expect(harness.fetchMock).toHaveBeenCalledTimes(2))
const body = JSON.parse(String(harness.fetchMock.mock.calls[1]?.[1]?.body))
expect(body.payload).toEqual({
hook_event_name: 'message_end',
role: 'assistant',
text: 'done',
session_id: 'omp-session-9'
})
expect(body.payload).not.toHaveProperty('session_file')
expect(harness.fetchMock.mock.calls[1]?.[0]).toBe('http://127.0.0.1:4321/hook/omp')
expect(harness.spawnMock).not.toHaveBeenCalled()
finishDeliveries[1]?.()
}
)

it.each(['pi', 'omp'] as const)(
'registers no status handlers for a nested %s subagent process',
(kind) => {
Expand Down
82 changes: 51 additions & 31 deletions src/main/pi/agent-status-extension-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,17 @@
import type { PiAgentKind } from '../../shared/pi-agent-kind'
import { getGeneratedNodeBoundedFileReaderSourceLines } from '../generated-node-bounded-file-reader'
import { getPiAgentStatusHandlerSourceLines } from './agent-status-handler-source'
import { getPiAgentStatusRuntimeDetectionSourceLines } from './agent-status-runtime-detection-source'

export const ORCA_PI_AGENT_STATUS_EXTENSION_FILE = 'orca-agent-status.ts'

export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): string {
// Why: OMP needs the file only to reject ephemeral sessions; disclose just its resume id.
const sessionMetadataSourceLines =
kind === 'pi'
? [
'let sessionMetadata: Record<string, unknown> = {}',
'let runtimeOmpSessionMetadata: Record<string, unknown> = {}',
'',
'function updateSessionMetadata(ctx: unknown): void {',
' const sessionManager = (ctx as { sessionManager?: { getSessionId?: () => unknown; getSessionFile?: () => unknown } } | null)?.sessionManager',
Expand All @@ -32,6 +35,18 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
' } : {}',
'}',
'',
'function updateRuntimeOmpSessionMetadata(ctx: unknown): void {',
' if (!isOmpRuntime()) return',
' const sessionManager = (ctx as { sessionManager?: { getSessionId?: () => unknown; getSessionFile?: () => unknown } } | null)?.sessionManager',
' const sessionId = sessionManager?.getSessionId?.()',
' const sessionFile = sessionManager?.getSessionFile?.()',
" runtimeOmpSessionMetadata = typeof sessionId === 'string' && sessionId && typeof sessionFile === 'string' && sessionFile ? { session_id: sessionId } : {}",
'}',
'',
'function getPostSessionMetadata(ompRuntime: boolean): Record<string, unknown> {',
' return ompRuntime ? runtimeOmpSessionMetadata : sessionMetadata',
'}',
'',
'function getPersistedSessionMetadata(): Record<string, unknown> {',
' const sessionFile = sessionMetadata.session_file',
" if (typeof sessionFile !== 'string' || !sessionFile) return {}",
Expand All @@ -46,11 +61,30 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
'}',
''
]
: []
: [
'let sessionMetadata: Record<string, unknown> = {}',
'',
'function updateSessionMetadata(ctx: unknown): void {',
' const sessionManager = (ctx as { sessionManager?: { getSessionId?: () => unknown; getSessionFile?: () => unknown } } | null)?.sessionManager',
' const sessionId = sessionManager?.getSessionId?.()',
' const sessionFile = sessionManager?.getSessionFile?.()',
" sessionMetadata = typeof sessionId === 'string' && sessionId && typeof sessionFile === 'string' && sessionFile ? { session_id: sessionId } : {}",
'}',
'',
'function updateRuntimeOmpSessionMetadata(ctx: unknown): void {',
' updateSessionMetadata(ctx)',
'}',
'',
'function getPostSessionMetadata(_ompRuntime: boolean): Record<string, unknown> {',
' return sessionMetadata',
'}',
''
]
// Why: Pi resumes from an existing transcript; OMP resumes directly by session id (#8962).
const payloadLine =
kind === 'pi'
? ' payload: { hook_event_name: hookEventName, ...getPersistedSessionMetadata(), ...extra },'
: ' payload: { hook_event_name: hookEventName, ...extra },'
? ' payload: { hook_event_name: hookEventName, ...(ompRuntime ? metadata : getPersistedSessionMetadata()), ...extra },'
: ' payload: { hook_event_name: hookEventName, ...metadata, ...extra },'

// Why: keep this string self-contained — it runs inside the pi process,
// so it cannot import from Orca's main bundle. fs/http coords come from
Expand All @@ -68,7 +102,7 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
'const HOOK_POST_TIMEOUT_MS = 1000',
...getGeneratedNodeBoundedFileReaderSourceLines({ typed: true }),
'let activePost = false',
'let pendingPost: { hookEventName: string; extra: Record<string, unknown> } | null = null',
'let pendingPost: { hookEventName: string; extra: Record<string, unknown>; metadata: Record<string, unknown>; ompRuntime: boolean } | null = null',
...sessionMetadataSourceLines,
'',
'// Why: re-reading the endpoint file on every event is cheap (small file,',
Expand Down Expand Up @@ -125,32 +159,16 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
' }',
'}',
'',
'function processName(value: unknown): string {',
" return String(value || '').split(/[\\\\/]/).pop()?.toLowerCase() || ''",
'}',
'',
'function resolveHookPath(): string {',
` const configuredPath = '/hook/${kind}'`,
' const executableNames = [',
' processName(process.title),',
' processName(process.env._),',
' processName(process.argv[1]),',
' processName(process.argv[0])',
' ]',
' const isOmpExecutable = executableNames.some((name) =>',
" ['omp', 'omp.js', 'omp.sh', 'omp.cmd', 'omp.exe', 'omp.bat'].includes(name)",
' )',
' // Why: a bare shell may launch either Pi or OMP after spawn. Runtime',
' // executable detection keeps that status labeled',
' // as OMP instead of silently reporting it as Pi.',
' if (isOmpExecutable) {',
" return '/hook/omp'",
' }',
' return configuredPath',
'}',
...getPiAgentStatusRuntimeDetectionSourceLines(kind),
'',
'function post(hookEventName: string, extra: Record<string, unknown> = {}): void {',
' pendingPost = { hookEventName, extra }',
' const ompRuntime = isOmpRuntime()',
' pendingPost = {',
' hookEventName,',
' extra,',
' metadata: getPostSessionMetadata(ompRuntime),',
' ompRuntime,',
' }',
' drainPosts()',
'}',
'',
Expand All @@ -159,7 +177,7 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
' const next = pendingPost',
' pendingPost = null',
' activePost = true',
' void postOnce(next.hookEventName, next.extra)',
' void postOnce(next.hookEventName, next.extra, next.metadata, next.ompRuntime)',
' .catch(() => {})',
' .finally(() => {',
' activePost = false',
Expand All @@ -169,12 +187,14 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
'',
'async function postOnce(',
' hookEventName: string,',
' extra: Record<string, unknown>',
' extra: Record<string, unknown>,',
' metadata: Record<string, unknown>,',
' ompRuntime: boolean',
'): Promise<void> {',
' const coords = resolveHookCoords()',
' const paneKey = process.env.ORCA_PANE_KEY',
' if (!coords.port || !coords.token || !paneKey) return',
' const url = `http://127.0.0.1:${coords.port}${resolveHookPath()}`',
' const url = `http://127.0.0.1:${coords.port}${resolveHookPath(ompRuntime)}`',
' const body = JSON.stringify({',
' paneKey,',
" launchToken: process.env.ORCA_AGENT_LAUNCH_TOKEN || '',",
Expand Down
Loading
Loading