Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

6.8 KB
Raw Blame
// Resting chats still own their conversation: native owner answers must pass released desktop activation gates and resume paneless agents.
// Drive the real host answer through that gate for both ways a chat stops running.

import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
import type { StructuredAgentSessionAdapter } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-adapter'
import { StructuredAgentSessionHost } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host'
import {
  HOST_TEST_NOW as NOW,
  HOST_TEST_SESSION as SESSION,
  HOST_TEST_THREAD as THREAD,
  hostTestAttachParams,
  resetHostTestOperationIds
} from '../../src/main/native-chat/agent-session-wire/structured-agent-session-host-test-data'
import { STRUCTURED_AGENT_SESSION_IDLE_MS } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-idle-sweep'
import type { AgentSessionRecordStore } from '../../src/main/runtime/agent-session-record-store'
import { openTestAgentSessionRecordStore } from '../../src/main/runtime/agent-session-record-store-test-harness'
import { useAppStore } from '../../src/renderer/src/store'
import { runWorktreeAgentActivationGate } from '../../src/renderer/src/lib/worktree-agent-activation-gate'
import { readWorktreeStructuredActivationInventory } from '../../src/renderer/src/lib/worktree-agent-structured-inventory'
import type { RuntimeMobileSessionTabsResult } from '../../src/shared/runtime-types'
import { openTestJournalHostDatabase } from '../../src/main/native-chat/agent-session-journal/journal-host-database-test-support'
import { createStructuredAgentSessionLogger } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-logger'
import { codexProviderHandle } from '../../src/shared/agent-session-provider-handle-encoding'
import { startsWhenPublished } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-instant-start.test-support'
import { NO_STRUCTURED_AGENTS } from '../../src/main/native-chat/agent-session-wire/structured-agent-session-adapter-router-test-support'

const WORKTREE = 'repo-1::/workspace/repo'

let root: string
let clock: number
let store: AgentSessionRecordStore
let host: StructuredAgentSessionHost
let closeSession: Mock<NonNullable<StructuredAgentSessionAdapter['closeSession']>>

function openHost(): void {
  host = new StructuredAgentSessionHost({
    agents: NO_STRUCTURED_AGENTS,
    logger: createStructuredAgentSessionLogger(),
    store,
    // A ready provider proves its start as soon as it is published.
    adapter: startsWhenPublished(
      {
        acquire: async ({ fence, spawnToken }) => ({
          acquisitionGeneration: `generation-${fence}`,
          process: {
            hostId: 'local',
            pid: 4242,
            processStartTimeMs: 1_700_000_000_000,
            spawnToken
          },
          link: {
            linkId: `link-${fence}`,
            handle: codexProviderHandle(THREAD),
            origin: store.getRecord(SESSION)?.providerHandleChain.length ? 'resumed' : 'created',
            mintedAtFence: fence,
            observedAt: NOW
          }
        }),
        closeSession,
        releaseAcquisition: async () => true,
        dispatch: async () => {
          throw new Error('dispatch is not exercised by this test')
        },
        cancelTurn: async () => ({ cancelled: false }),
        answerPrompt: async () => undefined,
        setOption: async () => undefined
      },
      () => host
    ),
    journalDatabase: openTestJournalHostDatabase(root),
    claimKeyId: 'key-1',
    mintSpawnToken: () => 'spawn-a',
    idleSweep: { intervalMs: 5 },
    probeOwner: async () => ({ outcome: 'pid-absent' }),
    now: () => clock
  })
}

/** The desktop's runtime bridge, answering the two reads the gate makes from the real host. */
function serveDesktopRuntime(): void {
  const tabs: RuntimeMobileSessionTabsResult = {
    worktree: WORKTREE,
    publicationEpoch: 'owner-status-test',
    snapshotVersion: 1,
    activeGroupId: null,
    activeTabId: null,
    activeTabType: null,
    tabs: [
      {
        type: 'agent-session',
        id: `structured-agent-session-${SESSION}`,
        title: 'Codex Chat',
        sessionId: SESSION,
        agent: 'codex',
        isActive: false
      }
    ]
  }
  const call = async ({ method, params }: { method: string; params: { sessionId?: string } }) => {
    if (method === 'session.tabs.list') {
      return { ok: true, result: tabs }
    }
    if (method === 'agentSession.handoffStatus') {
      try {
        return { ok: true, result: host.handoffStatus(params.sessionId ?? '') }
      } catch (error) {
        return {
          ok: false,
          error: { code: String(error), message: String(error) }
        }
      }
    }
    throw new Error(`Unexpected runtime method: ${method}`)
  }
  vi.stubGlobal('window', { api: { runtime: { call } } })
}

function activate(): ReturnType<typeof runWorktreeAgentActivationGate> {
  return runWorktreeAgentActivationGate(WORKTREE, {
    getState: () => useAppStore.getState(),
    listSessions: async () => [],
    listSurfaceOwners: async () => null,
    hasStructuredSession: readWorktreeStructuredActivationInventory,
    resume: () => 0
  })
}

beforeEach(async () => {
  root = await mkdtemp(join(tmpdir(), 'orca-owner-status-'))
  clock = NOW
  resetHostTestOperationIds()
  closeSession = vi.fn(async () => true)
  store = await openTestAgentSessionRecordStore(root)
  openHost()
  expect(await host.attach({ callerKey: 'client-1' }, hostTestAttachParams(null))).toMatchObject({
    ok: true
  })
  serveDesktopRuntime()
})

afterEach(async () => {
  vi.unstubAllGlobals()
  await host.flushAllStreamedEvents()
  await rm(root, { recursive: true, force: true })
})

describe('a chat at rest keeps its worktree activatable', () => {
  it('after the idle sweep stopped its agent and closed the conversation', async () => {
    clock += STRUCTURED_AGENT_SESSION_IDLE_MS + 1
    await vi.waitFor(() => expect(host.hasSession(SESSION)).toBe(false))
    expect(closeSession).toHaveBeenCalledWith(SESSION, undefined)

    expect(host.handoffStatus(SESSION)).toMatchObject({ owner: 'native' })
    expect(await activate()).toBe('structured')
  })

  it('after an app restart opens it for reading', async () => {
    await host.flushAllStreamedEvents()
    store = await openTestAgentSessionRecordStore(root)
    openHost()
    await host.seedSessionTabs([SESSION])
    await host.revealSession(SESSION)
    expect(host.hasSession(SESSION)).toBe(true)
    expect(store.getRecord(SESSION)?.lease).toMatchObject({
      claimStatus: 'released',
      ownerProcess: null
    })

    expect(host.handoffStatus(SESSION)).toMatchObject({ owner: 'native' })
    expect(await activate()).toBe('structured')
  })
})