# Pi Harness Integration Test

## Phase 5 Completion Checklist

### ✅ 1. WebSocket Integration
- [x] WebSocket handler exported from `websocket.ts`
- [x] Route `/api/pi/chat/ws` configured in `src/server.tsx`
- [x] Authentication middleware applied via token query param
- [x] Handler registered in handlers Map

### ✅ 2. REST API Integration
- [x] REST router exported from `rest.ts`
- [x] Router mounted in `src/servers/hono.ts` as `piRestRouter`
- [x] Protected routes middleware applied
- [x] All endpoints implemented:
  - GET `/api/pi/models` - List available models
  - POST `/api/pi/sessions` - List user sessions
  - GET `/api/pi/sessions/:sessionId` - Get session detail
  - PATCH `/api/pi/sessions/:sessionId` - Update session (rename)
  - DELETE `/api/pi/sessions/:sessionId` - Delete session
  - GET `/api/pi/sessions/search` - Search sessions

### ✅ 3. Type System
- [x] All types defined in `src/servers/api/pi/types.ts`
- [x] Legacy `chat-types.ts` updated to re-export new types
- [x] Deprecation notice added to `chat-types.ts`
- [x] No TypeScript compilation errors in Pi module

### ✅ 4. Architecture Verification
```
src/servers/api/pi/
├── types.ts              ✅ All message and session types
├── storage.ts            ✅ Session persistence to disk
├── pi-bridge.ts          ✅ Pi process spawning and RPC
├── session-manager.ts    ✅ In-memory session tracking
├── websocket.ts          ✅ WebSocket handler
└── rest.ts              ✅ REST endpoints
```

## Manual Testing Steps

### Test 1: REST Endpoints
```bash
# Get JWT token
TOKEN="your-jwt-token"

# List models
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:5000/api/pi/models

# List sessions
curl -X POST -H "Authorization: Bearer $TOKEN" \
  http://localhost:5000/api/pi/sessions

# Get session detail
curl -H "Authorization: Bearer $TOKEN" \
  http://localhost:5000/api/pi/sessions/{sessionId}

# Update session title
curl -X PATCH -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title": "New Title"}' \
  http://localhost:5000/api/pi/sessions/{sessionId}

# Delete session
curl -X DELETE -H "Authorization: Bearer $TOKEN" \
  http://localhost:5000/api/pi/sessions/{sessionId}

# Search sessions
curl -H "Authorization: Bearer $TOKEN" \
  "http://localhost:5000/api/pi/sessions/search?q=test"
```

### Test 2: WebSocket Connection
```javascript
const token = "your-jwt-token";
const ws = new WebSocket(`ws://localhost:5000/api/pi/chat/ws?token=${token}`);

ws.onopen = () => {
  console.log("Connected");
  // Start new chat
  ws.send(JSON.stringify({
    type: "chat",
    prompt: "Hello, world!",
    model: "gpt-4o",
    cwd: "/home/user/test"
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log("Received:", msg.type, msg);
};
```

### Test 3: Session Resume
```javascript
// First create a session (see Test 2)
// Then close the WebSocket

// Reconnect and resume
const ws2 = new WebSocket(`ws://localhost:5000/api/pi/chat/ws?token=${token}`);
ws2.onopen = () => {
  ws2.send(JSON.stringify({
    type: "resume",
    sessionId: "previous-session-id"
  }));
};

// Should receive sync:messages with full history
```

### Test 4: Stop Generation
```javascript
ws.send(JSON.stringify({ type: "stop" }));
// Should receive { type: "stopped" }
```

## Expected Behaviors

### WebSocket Flow
1. **Connect** → Authentication via token query param
2. **Send chat** → Receive `session:init` → Stream of `assistant:delta` → `tool:*` events → `result`
3. **Send resume** → Receive `sync:messages` with history
4. **Send stop** → Generation stops → Receive `stopped`
5. **Disconnect** → Idle timer starts (1 hour)

### Session Persistence
- Sessions saved to `{cwd}/.pi-sessions/{sessionId}/`
- `meta.json` - Session metadata
- `messages.json` - Full conversation history
- Updates written after each completed turn

### Error Handling
- Invalid token → 401 Unauthorized
- Invalid session ID → 404 Not Found
- Pi process crash → Error message to client
- Malformed JSON → Error message, connection stays open

## Integration Status

**Phase 5: COMPLETE ✅**

All components properly wired:
- ✅ WebSocket handler integrated
- ✅ REST endpoints integrated
- ✅ Type system unified
- ✅ No compilation errors
- ✅ Architecture matches design document

**Next Steps**: Manual testing with real client to verify end-to-end functionality.
