import { describe, test, expect, beforeEach, mock } from 'bun:test' import { mockConfigModule } from './helpers/mock-config' mock.module('../config', () => mockConfigModule({ pollTimeout: 1 })) import { Hono } from 'hono' import { storeBindSession, storeCreateEnvironment, storeCreateSession, storeGetActiveWorkItemBySession, storeGetPendingWorkItem, storeReset, } from '../store' import { issueToken } from '../auth/token' import { getDb } from '../db/sqlite' import webSessions from '../routes/web/sessions' import webEnvironments from '../routes/web/environments' import { reconnectWorkForEnvironment } from '../services/work-dispatch' import { normalizeSessionCwd, normalizeWorkspaceDirs } from '../services/paths' function createApp() { const app = new Hono() app.route('/web', webSessions) app.route('/web', webEnvironments) return app } function auth(user: string): string { return `Bearer ${issueToken(user).token}` } /** An environment owned by user-1 with a startup dir + one quick pick. */ function makeOwnedEnv(overrides?: Record) { return storeCreateEnvironment({ secret: 's', machineName: 'build-box', directory: '/srv/app', workspaceDirs: ['/srv/app', '/srv/lib'], workerType: 'saluzi', ownerUserId: 'user-1', ...overrides, }) } describe('session working directory', () => { let app: Hono beforeEach(() => { storeReset() getDb() app = createApp() }) test('normalizeSessionCwd accepts absolute and ~/ paths, rejects relative', () => { expect(normalizeSessionCwd('/srv/app/../lib')).toEqual({ ok: true, cwd: '/srv/lib', }) expect(normalizeSessionCwd('~/projects')).toEqual({ ok: true, cwd: '~/projects', }) expect(normalizeSessionCwd('C:\\work\\app')).toEqual({ ok: true, cwd: 'C:\\work\\app', }) expect(normalizeSessionCwd('relative/path').ok).toBe(false) expect(normalizeSessionCwd('').ok).toBe(false) expect(normalizeSessionCwd('a\0b').ok).toBe(false) }) test('normalizeWorkspaceDirs dedupes, drops relative paths, falls back to directory', () => { expect( normalizeWorkspaceDirs(['/srv/lib', '/srv/lib/', 'rel'], '/srv/app'), ).toEqual(['/srv/lib']) expect(normalizeWorkspaceDirs(undefined, '/srv/app')).toEqual(['/srv/app']) }) test('POST /web/sessions persists cwd and dispatches it on the work item', async () => { const env = makeOwnedEnv() const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-1'), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id: env.id, cwd: '/srv/lib', spawn_mode: 'same-dir', }), }) expect(res.status).toBe(200) const body = (await res.json()) as { id: string; cwd: string } expect(body.cwd).toBe('/srv/lib') const work = storeGetActiveWorkItemBySession(body.id) expect(work?.cwd).toBe('/srv/lib') expect(work?.spawnMode).toBe('same-dir') }) test('POST /web/sessions defaults cwd to the machine startup directory', async () => { const env = makeOwnedEnv() const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-1'), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id: env.id }), }) expect(res.status).toBe(200) const body = (await res.json()) as { id: string; cwd: string } expect(body.cwd).toBe('/srv/app') expect(storeGetActiveWorkItemBySession(body.id)?.cwd).toBe('/srv/app') }) test('POST /web/sessions rejects a relative cwd', async () => { const env = makeOwnedEnv() const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-1'), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id: env.id, cwd: 'relative/dir' }), }) expect(res.status).toBe(400) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('invalid_cwd') }) test('POST /web/sessions enforces machine access (non-owner → 403)', async () => { const env = makeOwnedEnv() const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-2'), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id: env.id }), }) expect(res.status).toBe(403) }) test('in-process repl workers reject a different cwd', async () => { const env = makeOwnedEnv({ workerType: 'repl' }) const res = await app.request('/web/sessions', { method: 'POST', headers: { Authorization: auth('user-1'), 'Content-Type': 'application/json', }, body: JSON.stringify({ environment_id: env.id, cwd: '/srv/lib' }), }) expect(res.status).toBe(409) const body = (await res.json()) as { error: { type: string } } expect(body.error.type).toBe('cwd_not_supported') }) test('legacy sessions without cwd fall back to the environment directory on reconnect', async () => { const env = makeOwnedEnv() const session = storeCreateSession({ environmentId: env.id }) expect(session.cwd).toBeNull() await reconnectWorkForEnvironment(env.id) expect(storeGetPendingWorkItem(env.id)?.cwd).toBe('/srv/app') }) test('reconnect keeps an explicit session cwd', async () => { const env = makeOwnedEnv() const session = storeCreateSession({ environmentId: env.id, cwd: '/srv/lib', spawnMode: 'worktree', }) await reconnectWorkForEnvironment(env.id) const work = storeGetPendingWorkItem(env.id) expect(work?.sessionId).toBe(session.id) expect(work?.cwd).toBe('/srv/lib') expect(work?.spawnMode).toBe('worktree') }) test('GET /web/environments exposes workspace_dirs and capacity', async () => { makeOwnedEnv({ maxSessions: 4 }) const res = await app.request('/web/environments', { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as Array<{ workspace_dirs: string[] max_sessions: number active_sessions: number }> expect(body[0]).toMatchObject({ workspace_dirs: ['/srv/app', '/srv/lib'], max_sessions: 4, active_sessions: 0, }) }) test('recent-dirs returns distinct session cwds, newest first', async () => { const env = makeOwnedEnv() for (const cwd of ['/srv/app', '/srv/lib', '/srv/app']) { const session = storeCreateSession({ environmentId: env.id, cwd }) storeBindSession(session.id, 'user-1') } const res = await app.request(`/web/environments/${env.id}/recent-dirs`, { headers: { Authorization: auth('user-1') }, }) expect(res.status).toBe(200) const body = (await res.json()) as { dirs: string[] } expect(new Set(body.dirs)).toEqual(new Set(['/srv/app', '/srv/lib'])) expect(body.dirs.length).toBe(2) }) test('recent-dirs is forbidden for a non-owner', async () => { const env = makeOwnedEnv() const res = await app.request(`/web/environments/${env.id}/recent-dirs`, { headers: { Authorization: auth('user-2') }, }) expect(res.status).toBe(403) }) })