import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' // Mock config before any module imports mock.module('../config', () => mockConfigModule()) import { Hono } from 'hono' import type { Database } from 'bun:sqlite' import { randomUUID } from 'node:crypto' import { tmpdir } from 'node:os' import { resolve } from 'node:path' import v1Environments from '../routes/v1/environments' import webEnvironments from '../routes/web/environments' import { storeReset, storeCreateEnvironment, storeGetEnvironment, storeUpdateEnvironment, storeListActiveEnvironmentsWithTeam, } from '../store' import { initDatabase, resetDbSingleton, getDb } from '../db/sqlite' import { issueSessionToken } from '../auth/session' import { createUserDirectly } from './helpers/fixtures' import { createSession, archiveSession } from '../services/session' import { storeBindSession } from '../store' /** * Session Attach P2 — wait mode: * * - POST /v1/environments/bridge persists session_mode:'attach'. * - GET /v1/environments/:id/assignment returns the first open non-ACP * session on the env (assigned:false until the Web UI binds one). * Gated on env ownership (admin bypasses; unowned envs stay open). * - GET /web/environments surfaces attach_waiting for waiting workers. */ function freshDb(): Database { try { resetDbSingleton() } catch {} const path = resolve( tmpdir(), `rcs-attach-wait-${randomUUID().replace(/-/g, '').slice(0, 8)}.db`, ) return initDatabase(path) } function createUser(db: Database): { id: string; username: string } { const username = `user_${randomUUID().slice(0, 6)}` const user = createUserDirectly(db, { username, role: 'member' }) return { id: user.id, username: user.username } } function rctAuth(userId: string): string { return `Bearer ${issueSessionToken(userId, getDb()).accessToken}` } const ADMIN_KEY = { Authorization: 'Bearer test-api-key' } const JSON_HDRS = { 'Content-Type': 'application/json' } function createApp() { const app = new Hono() app.route('/v1/environments', v1Environments) app.route('/web', webEnvironments) return app } describe('Session Attach wait mode', () => { let app: Hono let db: Database let owner: { id: string; username: string } beforeEach(() => { db = freshDb() storeReset() app = createApp() owner = createUser(db) }) test('POST /bridge with session_mode=attach persists the mode', async () => { const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...JSON_HDRS, ...ADMIN_KEY, 'X-User-Id': owner.username }, body: JSON.stringify({ machine_name: 'mac1', session_mode: 'attach' }), }) expect(res.status).toBe(200) const envId = ((await res.json()) as { environment_id: string }) .environment_id expect(storeGetEnvironment(envId)?.sessionMode).toBe('attach') }) test('POST /bridge without session_mode stays create-mode', async () => { const res = await app.request('/v1/environments/bridge', { method: 'POST', headers: { ...JSON_HDRS, ...ADMIN_KEY, 'X-User-Id': owner.username }, body: JSON.stringify({ machine_name: 'mac1' }), }) expect(res.status).toBe(200) const envId = ((await res.json()) as { environment_id: string }) .environment_id expect(storeGetEnvironment(envId)?.sessionMode ?? null).toBeNull() }) test('assignment: unassigned env → assigned:false', async () => { const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) // Age the heartbeat past the disconnect timeout, then verify the poll // refreshes it (P0-2: without this the disconnect monitor kills the // waiting env after 5 minutes and the CLI dead-waits its deadline). const stale = new Date(Date.now() - 10 * 60 * 1000) storeUpdateEnvironment(env.id, { lastPollAt: stale }) const before = storeGetEnvironment(env.id)?.lastPollAt?.getTime() const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ assigned: false }) const after = storeGetEnvironment(env.id)?.lastPollAt?.getTime() expect(after).not.toBe(before) expect(after ?? 0).toBeGreaterThan(stale.getTime()) }) test('assignment: owned env + owner rct token → 200 (worker polls as itself)', async () => { const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { Authorization: rctAuth(owner.id) }, }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ assigned: false }) }) test('assignment: owned env + stranger rct token → 403, heartbeat NOT refreshed', async () => { // Assignment discloses the env's bound session AND is its liveness // signal — neither may be driven by a third party. const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) const stale = new Date(Date.now() - 10 * 60 * 1000) storeUpdateEnvironment(env.id, { lastPollAt: stale }) const stranger = createUser(db) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { Authorization: rctAuth(stranger.id) }, }) expect(res.status).toBe(403) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('forbidden') // touchEnvironmentActivity runs only AFTER the gate — a 403 must not keep a dead // env looking alive. expect(storeGetEnvironment(env.id)?.lastPollAt?.getTime()).toBe( stale.getTime(), ) }) test('assignment: unowned env (claim pending) + any auth → 200 assigned:false', async () => { // Two-phase wait (claim → attach): while unowned there is nothing to // disclose, so the poll stays open to any authenticated caller. const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'unclaimed', sessionMode: 'attach', }) const stranger = createUser(db) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { Authorization: rctAuth(stranger.id) }, }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ assigned: false }) }) test('assignment: disconnected env + authorized caller → reactivated, not 404', async () => { // A wait-mode worker whose env the disconnect monitor flipped (laptop // sleep during the 24h wait, pre-fix claim-wait, etc.) must recover on // its next poll instead of dead-waiting on swallowed 404s — the CLI // ignores assignment errors until its deadline. const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) storeUpdateEnvironment(env.id, { status: 'disconnected' }) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ assigned: false }) expect(storeGetEnvironment(env.id)?.status).toBe('active') }) test('assignment: disconnected env + stranger → 403, env NOT reactivated', async () => { // Same invariant as the heartbeat test above: a 403 must not resurrect // or keep alive an env the caller has no business touching. const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) storeUpdateEnvironment(env.id, { status: 'disconnected' }) const stranger = createUser(db) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { Authorization: rctAuth(stranger.id) }, }) expect(res.status).toBe(403) expect(storeGetEnvironment(env.id)?.status).toBe('disconnected') }) test('assignment: deregistered env → 404 (terminal)', async () => { const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) storeUpdateEnvironment(env.id, { status: 'deregistered' }) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(404) }) test('assignment: session bound to the env (web attach) → assigned with session id', async () => { const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) const session = createSession({ environment_id: env.id, title: 'Team session', source: 'web', }) storeBindSession(session.id, owner.id, 'user') const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(200) const body = (await res.json()) as { assigned: boolean session_id?: string } expect(body.assigned).toBe(true) expect(body.session_id).toBe(session.id) }) test('assignment: archived sessions do not satisfy the assignment', async () => { const env = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'mac1', ownerUserId: owner.id, sessionMode: 'attach', }) const session = createSession({ environment_id: env.id, title: 'Archived session', source: 'web', }) archiveSession(session.id) const res = await app.request(`/v1/environments/${env.id}/assignment`, { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(200) expect(await res.json()).toEqual({ assigned: false }) }) test('assignment: unknown env → 404', async () => { const res = await app.request('/v1/environments/env_missing/assignment', { headers: { ...ADMIN_KEY }, }) expect(res.status).toBe(404) }) test('web environments exposes attach_waiting for waiting workers', async () => { storeCreateEnvironment({ secret: 'test-api-key', machineName: 'waiting-cli', ownerUserId: owner.id, sessionMode: 'attach', }) // A create-mode env with a bound session — never attach_waiting. const busyEnv = storeCreateEnvironment({ secret: 'test-api-key', machineName: 'busy-cli', ownerUserId: owner.id, }) createSession({ environment_id: busyEnv.id, title: 's', source: 'web', }) const res = await app.request('/web/environments', { headers: { Authorization: rctAuth(owner.id) }, }) expect(res.status).toBe(200) const envs = (await res.json()) as Array<{ machine_name: string attach_waiting?: boolean }> const waiting = envs.find(e => e.machine_name === 'waiting-cli') const busy = envs.find(e => e.machine_name === 'busy-cli') expect(waiting?.attach_waiting).toBe(true) expect(busy?.attach_waiting ?? false).toBe(false) }) })