feat(sessions): add multi-agent support and credential injection for interactive sessions
Title
feat(sessions): add multi-agent support, credential injection, and fix chat replay bugs
Summary
Add comprehensive agent credential injection and multi-agent support for interactive sessions (terminal + chat), enabling Gemini and Claude Vertex AI (with support for other agent types in the credential service). This PR also resolves critical UI grouping and log replay issues in the interactive session chat interface and adds Markdown support for chat messages.
Changes
Agent Credential Service
- Centralized credential retrieval infrastructure
- Supports Claude (api-key, oauth-token, max-subscription, vertex-ai) and Gemini.
- Credential service infrastructure supports additional agent types (Codex, Copilot, Groq, OpenClaw, OpenCode), with session integration currently focused on Claude and Gemini.
Multi-Agent Session Support
- Terminal and chat now respect repo's
defaultAgentType - Dynamic model switching mid-session
- Agent-specific event parsers (Claude vs Gemini)
- Integrated with existing header model dropdown
WebSocket & Chat Improvements
- Fix: Resolved message grouping and log replay issues in the session chat interface by replacing fragile component refs with synchronous, state-based message reconstruction.
- Fix: Improved error context preservation when authentication fails, making debugging Vertex AI issues significantly easier.
- Fix: Corrected agent execution path to explicitly validate/reject unsupported agent types in the WebSocket handler.
- Fix: Added missing
readyStatecheck inhandleModelChangeto prevent WebSocket errors during rapid model switching. - Added Markdown support for chat messages via
ChatMarkdownintegration. - Option in chat area to enable/disable display of system, thinking and tool messages
- Added keepalive ping (20s) to prevent idle disconnects.
- Filtered harmless logs (e.g., shell/git output).
Shared Utilities
buildSetupFilesScript()utility for file injection (eliminates duplication).
Testing
✅ All new tests (13/13) passing.
✅ Verified chat replay ordering and message grouping.
✅ Typechecking (pnpm turbo typecheck) passed.
✅ All tests (pnpm turbo test) verified with Node v24.16.0.
Review
Solid PR overall — real fixes (terminal hardcoded to claude-code, chat missing Vertex, WS idle disconnects), good test coverage on agent-credential-service, and the centralization shape is right. A few things to address before merging.
Blockers
1. session-chat.ts runs claude for every non-Gemini agent.
In the new agent-command branch:
} else {
// claude-code, codex, copilot, etc.
agentCommand = `claude -p '${escapedPrompt}' ${modelFlag} --output-format stream-json --verbose --dangerously-skip-permissions < /dev/null || true`;
}
The comment lists agents that would silently invoke claude instead of their own binaries. The PR description says this enables "all other agent types to work in session environments," but only Claude and Gemini actually do today. Either add per-agent branches (codex/copilot/groq/opencode/openclaw) or explicitly reject unsupported agent types in the chat WS handler.
2. Six console.log debug statements left in apps/web/src/components/session-chat.tsx.
Search for [SessionChat] — logging external model change, agentType state changes, model option counts, model-validation resets, and incoming WS model/agentType updates. Strip them or gate behind a debug flag.
3. Shell-expansion risk in apps/api/src/utils/setup-files.ts.
`echo "${message}"`,
message is interpolated unescaped inside a double-quoted bash echo, which expands $var, $(...), and backticks. Today's callers pass constants so there's no exploit, but the API is unsafe by construction. Either escape, switch to a single-quoted echo, or inline the constant.
4. Dangling JSDoc at apps/api/src/ws/session-chat.ts:345 — /** Build auth environment variables for the claude process in the pod. */ is preserved while the buildAuthEnv function it documents is deleted. Drop the comment.
5. The "centralized service" only covers 3 of ~6 call sites. The PR description says credential retrieval is "centralized," but the same auth-mode logic still lives in:
apps/api/src/workers/workflow-worker.ts:366-419(Standalone Tasks)apps/api/src/workers/pr-review-worker.ts:212+400(review subtasks)apps/api/src/ws/optio-chat.ts:343(Optio chat)
Future drift across these sites is exactly what centralization is meant to prevent. Either fold them into getAgentCredentials here or drop "centralized" from the description and file a follow-up so it isn't forgotten.
Should-fix
6. Lost upstream error context in task-worker strict validation.
Old: Max subscription auth failed: ${authResult.error ?? "Token not available"} — surfaced auth-proxy errors.
New: just "Max subscription auth failed: Token not available" (task-worker.ts:743). The real authResult.error is logged as a warn inside getAgentCredentials and never reaches the task-failure surface. Either propagate it via a thrown error from the credential service, or have the service return { env, errors? } so callers can surface it.
7. claudeVertexServiceAccountKey: undefined warrants verification.
task-worker.ts now hardcodes this to undefined on the assumption the credential service handles the SA key via setupFiles. If the adapter still consumes that field for anything other than the file write (e.g., to derive an env var the new service doesn't set), Vertex AI tasks break silently. Worth a comment in buildContainerConfig or an integration test that exercises the Vertex path through task-worker end-to-end (current tests only cover agent-credential-service in isolation).
8. Pervasive as any casts in the new service and WS handlers defeat the type safety this PR is supposed to add. Auth modes should be a discriminated union/enum, and (repoConfig?.defaultAgentType || "claude-code") as any in the WS handlers should use the new exported AgentType.
9. No tests for buildSetupFilesScript. It's a shell-script-builder doing base64+python3 codegen and has the unsafe interpolation noted above; deserves at least a snapshot test. Also note repo-pool-service.ts:1027 already has a similar Python-based file writer with a behavior the new util omits (/opt/optio/ → /home/agent/optio/ path rewrite). Worth a one-liner explaining why the rewrite isn't needed in WS context.
10. Missing readyState guard in handleModelChange (session-chat.tsx):
wsRef.current?.send(JSON.stringify({ type: "set_model", model: newModel }));
Other handlers in this file check socket.readyState === 1 first. If the user clicks the model dropdown while the WS is connecting or closed, .send() throws.
Nits
- Vertex secret scoping is mixed:
CLAUDE_VERTEX_PROJECT_ID/_REGIONare fetched withoutuserId, but_SERVICE_ACCOUNT_KEYis fetched withuserId. May be intentional (per-user SA keys, shared project) — worth a comment. - Pre-flight token validation in
task-worker.ts:632-648is now logically separate from the credential fetch but still tightly coupled tooauth-tokenmode. Consider folding it intogetAgentCredentials("claude-code", …)so workflow-worker/pr-review-worker benefit once they migrate. agentType === "gemini"branching is hardcoded in two places insession-chat.ts(command building, parser selection). Fine for two agents; a small dispatch table will be cleaner once Codex/Copilot follow.- Tests don't cover:
oauth-tokenmode with no token (warns vs throws), GeminiGOOGLE_GENAI_API_KEYlegacy fallback, non-"Secret not found" errors from the secret service.
Thanks for the feedback! I've addressed the blocking items. I have also fixed couple of more issues and added markdown support (PR description upated)
- Unsupported agent types: Added explicit agent type validation in the session chat WebSocket handler to reject unsupported types instead of falling back to the default Claude agent.
- ReadyState check: Added
readyState === 1guard tohandleModelChangeinsession-chat.tsxto prevent.send()errors during rapid model switching. - Auth error context: Updated
task-worker.tsto surface theagentCredentials.errorcontext in exception messages, ensuring auth failures (especially Vertex AI) provide clear debug information.
The other deferred items have been noted as follow-ups.