diff --git a/docs/superpowers/plans/2026-03-22-assistant-ux-redesign.md b/docs/superpowers/plans/2026-03-22-assistant-ux-redesign.md new file mode 100644 index 0000000..35a4ad4 --- /dev/null +++ b/docs/superpowers/plans/2026-03-22-assistant-ux-redesign.md @@ -0,0 +1,967 @@ +# Assistant UX Redesign Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Redesign the Telegram Assistant UX to be context-aware, user-friendly, and capable of guiding users through all OpenACP features. + +**Architecture:** Rewrite 3 files in the Telegram adapter: assistant.ts (welcome message builder + system prompt), commands.ts (menu keyboard + help text + interactive session creation), adapter.ts (use new welcome builder). Add tests for pure logic functions (welcome message builder, system prompt builder). No architecture changes β€” same routing, same startup flow. + +**Tech Stack:** TypeScript, grammY (Telegram bot), vitest (tests) + +**Spec:** `docs/superpowers/specs/2026-03-22-assistant-ux-redesign.md` + +--- + +### Task 1: Welcome Message Builder + +Add `buildWelcomeMessage()` to `assistant.ts` β€” a pure logic function that generates context-aware welcome text. + +**Files:** +- Modify: `src/adapters/telegram/assistant.ts:60-65` (add WelcomeContext interface + buildWelcomeMessage function) +- Create: `src/__tests__/welcome-message.test.ts` + +- [ ] **Step 1: Write tests for buildWelcomeMessage** + +Create `src/__tests__/welcome-message.test.ts`: + +```typescript +import { describe, it, expect } from "vitest"; +import { buildWelcomeMessage, type WelcomeContext } from "../adapters/telegram/assistant.js"; + +describe("buildWelcomeMessage", () => { + it("shows no-sessions variant when totalCount is 0", () => { + const ctx: WelcomeContext = { + activeCount: 0, + errorCount: 0, + totalCount: 0, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("OpenACP is ready"); + expect(msg).toContain("No sessions yet"); + expect(msg).not.toContain("Agents:"); + }); + + it("shows active variant when there are active sessions and no errors", () => { + const ctx: WelcomeContext = { + activeCount: 2, + errorCount: 0, + totalCount: 5, + agents: ["claude", "codex"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("2 active / 5 total"); + expect(msg).toContain("claude (default)"); + expect(msg).toContain("codex"); + expect(msg).not.toContain("errors"); + }); + + it("shows error variant when there are error sessions", () => { + const ctx: WelcomeContext = { + activeCount: 1, + errorCount: 2, + totalCount: 5, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("1 active"); + expect(msg).toContain("2 errors"); + expect(msg).toContain("5 total"); + expect(msg).toContain("ask me to check"); + }); + + it("shows fallback variant when all sessions are finished (0 active, 0 errors)", () => { + const ctx: WelcomeContext = { + activeCount: 0, + errorCount: 0, + totalCount: 3, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("0 active / 3 total"); + expect(msg).toContain("Agents:"); + }); + + it("errors variant takes priority over active variant", () => { + const ctx: WelcomeContext = { + activeCount: 3, + errorCount: 1, + totalCount: 10, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("errors"); + expect(msg).toContain("ask me to check"); + }); +}); +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `pnpm test -- src/__tests__/welcome-message.test.ts` +Expected: FAIL β€” `buildWelcomeMessage` not exported / does not exist + +- [ ] **Step 3: Implement buildWelcomeMessage in assistant.ts** + +Add the `WelcomeContext` interface and `buildWelcomeMessage` function to `src/adapters/telegram/assistant.ts` after the existing `AssistantContext` interface (after line 65): + +```typescript +export interface WelcomeContext { + activeCount: number; + errorCount: number; + totalCount: number; + agents: string[]; + defaultAgent: string; +} + +export function buildWelcomeMessage(ctx: WelcomeContext): string { + const { activeCount, errorCount, totalCount, agents, defaultAgent } = ctx; + + const agentList = agents + .map((a) => `${a}${a === defaultAgent ? " (default)" : ""}`) + .join(", "); + + // Variant 1: No sessions + if (totalCount === 0) { + return `πŸ‘‹ OpenACP is ready!\n\nNo sessions yet. Tap πŸ†• New Session to start, or ask me anything!`; + } + + // Variant 2: Has errors + if (errorCount > 0) { + return ( + `πŸ‘‹ OpenACP is ready!\n\n` + + `πŸ“Š ${activeCount} active, ${errorCount} errors / ${totalCount} total\n` + + `⚠️ ${errorCount} session${errorCount > 1 ? "s have" : " has"} errors β€” ask me to check if you'd like.\n\n` + + `Agents: ${agentList}` + ); + } + + // Variant 3/4: Has active or fallback + return ( + `πŸ‘‹ OpenACP is ready!\n\n` + + `πŸ“Š ${activeCount} active / ${totalCount} total\n` + + `Agents: ${agentList}` + ); +} +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pnpm test -- src/__tests__/welcome-message.test.ts` +Expected: All 5 tests PASS + +- [ ] **Step 5: Wire buildWelcomeMessage into adapter.ts** + +In `src/adapters/telegram/adapter.ts`, replace the inline welcome message logic (lines ~303-325) with a call to `buildWelcomeMessage()`. + +Replace: +```typescript +const config = this.core.configManager.get(); +const agents = this.core.agentManager.getAvailableAgents(); +const agentList = agents + .map((a) => `${escapeHtml(a.name)}${a.name === config.defaultAgent ? " (default)" : ""}`) + .join(", "); +const workspace = escapeHtml(config.workspace.baseDir); +const allRecords = this.core.sessionManager.listRecords(); +const activeCount = allRecords.filter(r => r.status === 'active' || r.status === 'initializing').length; + +const welcomeText = + `πŸ‘‹ OpenACP Assistant is online.\n\n` + + `Available agents: ${agentList}\n` + + `Workspace: ${workspace}\n` + + `Sessions: ${activeCount} active / ${allRecords.length} total\n\n` + + `Select an action:`; +``` + +With: +```typescript +const config = this.core.configManager.get(); +const agents = this.core.agentManager.getAvailableAgents(); +const allRecords = this.core.sessionManager.listRecords(); + +const welcomeText = buildWelcomeMessage({ + activeCount: allRecords.filter(r => r.status === 'active' || r.status === 'initializing').length, + errorCount: allRecords.filter(r => r.status === 'error').length, + totalCount: allRecords.length, + agents: agents.map(a => a.name), + defaultAgent: config.defaultAgent, +}); +``` + +Add `buildWelcomeMessage` to the import from `./assistant.js`. + +- [ ] **Step 6: Build and verify no TypeScript errors** + +Run: `pnpm build` +Expected: Clean build, no errors + +- [ ] **Step 7: Commit** + +```bash +git add src/adapters/telegram/assistant.ts src/adapters/telegram/adapter.ts src/__tests__/welcome-message.test.ts +git commit -m "feat(assistant): add context-aware welcome message builder" +``` + +--- + +### Task 2: Menu Keyboard Redesign + +Remove New Chat and Cancel from menu, reorganize layout. + +**Files:** +- Modify: `src/adapters/telegram/commands.ts:37-53` (buildMenuKeyboard) +- Modify: `src/adapters/telegram/commands.ts:61-116` (setupMenuCallbacks β€” remove m:newchat and m:cancel cases) + +- [ ] **Step 1: Update buildMenuKeyboard()** + +In `src/adapters/telegram/commands.ts`, replace `buildMenuKeyboard()` (lines 37-53): + +```typescript +export function buildMenuKeyboard(): InlineKeyboard { + return new InlineKeyboard() + .text("πŸ†• New Session", "m:new") + .text("πŸ“‹ Sessions", "m:topics") + .row() + .text("πŸ“Š Status", "m:status") + .text("πŸ€– Agents", "m:agents") + .row() + .text("πŸ”— Integrate", "m:integrate") + .text("❓ Help", "m:help") + .row() + .text("πŸ”„ Restart", "m:restart") + .text("⬆️ Update", "m:update"); +} +``` + +- [ ] **Step 2: Remove m:newchat and m:cancel from setupMenuCallbacks** + +In `setupMenuCallbacks()`, remove these two cases from the switch statement: +```typescript +case "m:newchat": + await handleNewChat(ctx, core, chatId); + break; +case "m:cancel": + await handleCancel(ctx, core); + break; +``` + +Keep all `m:cleanup:*` cases and all other cases unchanged. + +- [ ] **Step 3: Build and verify** + +Run: `pnpm build` +Expected: Clean build + +- [ ] **Step 4: Commit** + +```bash +git add src/adapters/telegram/commands.ts +git commit -m "feat(menu): reorganize keyboard, remove New Chat and Cancel buttons" +``` + +--- + +### Task 3: Help Text Rewrite + +Rewrite `/help` output to group commands by use case. + +**Files:** +- Modify: `src/adapters/telegram/commands.ts:638-653` (handleHelp function) + +- [ ] **Step 1: Rewrite handleHelp()** + +Replace the `handleHelp` function body: + +```typescript +async function handleHelp(ctx: Context): Promise { + await ctx.reply( + `πŸ“– OpenACP Help\n\n` + + `πŸš€ Getting Started\n` + + `Tap πŸ†• New Session to start coding with AI.\n` + + `Each session gets its own topic β€” chat there to work with the agent.\n\n` + + `πŸ’‘ Common Tasks\n` + + `/new [agent] [workspace] β€” Create new session\n` + + `/cancel β€” Cancel session (in session topic)\n` + + `/status β€” Show session or system status\n` + + `/sessions β€” List all sessions\n` + + `/agents β€” List available agents\n\n` + + `βš™οΈ System\n` + + `/restart β€” Restart OpenACP\n` + + `/update β€” Update to latest version\n` + + `/integrate β€” Manage agent integrations\n` + + `/menu β€” Show action menu\n\n` + + `πŸ”’ Session Options\n` + + `/enable_dangerous β€” Auto-approve permissions\n` + + `/disable_dangerous β€” Restore permission prompts\n` + + `/handoff β€” Continue session in terminal\n\n` + + `πŸ’¬ Need help? Just ask me in this topic!`, + { parse_mode: "HTML" }, + ); +} +``` + +- [ ] **Step 2: Build and verify** + +Run: `pnpm build` +Expected: Clean build + +- [ ] **Step 3: Commit** + +```bash +git add src/adapters/telegram/commands.ts +git commit -m "feat(help): rewrite help text grouped by use case" +``` + +--- + +### Task 4: System Prompt Rewrite + +Complete rewrite of `buildAssistantSystemPrompt()` with product context, action playbook, and guidelines. + +**Files:** +- Modify: `src/adapters/telegram/assistant.ts:67-132` (buildAssistantSystemPrompt function) +- Create: `src/__tests__/assistant-prompt.test.ts` + +- [ ] **Step 1: Write tests for the new system prompt** + +Create `src/__tests__/assistant-prompt.test.ts`: + +```typescript +import { describe, it, expect } from "vitest"; +import { buildAssistantSystemPrompt, type AssistantContext } from "../adapters/telegram/assistant.js"; + +function makeCtx(overrides?: Partial): AssistantContext { + return { + config: { + agents: { claude: { command: "claude", args: [] }, codex: { command: "codex", args: [] } }, + defaultAgent: "claude", + workspace: { baseDir: "~/openacp-workspace" }, + } as any, + activeSessionCount: 2, + totalSessionCount: 5, + topicSummary: [ + { status: "active", count: 2 }, + { status: "finished", count: 3 }, + ], + ...overrides, + }; +} + +describe("buildAssistantSystemPrompt", () => { + it("includes product context", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("OpenACP Assistant"); + expect(prompt).toContain("Agent Client Protocol"); + }); + + it("includes current state", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("Active sessions: 2"); + expect(prompt).toContain("claude"); + expect(prompt).toContain("codex"); + }); + + it("includes action playbook", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("openacp api status"); + expect(prompt).toContain("openacp api cancel"); + expect(prompt).toContain("openacp api health"); + expect(prompt).toContain("openacp api cleanup"); + expect(prompt).toContain("openacp api config"); + }); + + it("includes guidelines about self-execution", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("openacp api"); + expect(prompt).toContain("confirm"); + expect(prompt).toContain("same language"); + }); + + it("does not include old Telegram bot commands section", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).not.toContain("Session Management Commands"); + expect(prompt).not.toContain("These are Telegram bot commands"); + }); + + it("includes workspace explanation in create session playbook", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("workspace"); + expect(prompt).toContain("project directory"); + }); +}); +``` + +- [ ] **Step 2: Run tests to see current state** + +Run: `pnpm test -- src/__tests__/assistant-prompt.test.ts` +Expected: Some tests FAIL (old prompt doesn't have product context, playbook, etc.) + +- [ ] **Step 3: Rewrite buildAssistantSystemPrompt()** + +Replace the entire `buildAssistantSystemPrompt` function in `src/adapters/telegram/assistant.ts` (lines 67-132): + +```typescript +export function buildAssistantSystemPrompt(ctx: AssistantContext): string { + const { config, activeSessionCount, totalSessionCount, topicSummary } = ctx; + const agentNames = Object.keys(config.agents).join(", "); + const topicBreakdown = + topicSummary.map((s) => `${s.status}: ${s.count}`).join(", ") || "none"; + + return `You are the OpenACP Assistant β€” a helpful guide for managing AI coding sessions. + +OpenACP bridges messaging platforms (like Telegram) to AI coding agents (like Claude Code) via the Agent Client Protocol (ACP). Users chat here, and their messages are routed to AI agents that can read, write, and execute code in real workspaces. + +Each session runs in its own Telegram topic. You help users create sessions, monitor them, troubleshoot issues, and manage the system. + +## Current State +- Active sessions: ${activeSessionCount} / ${totalSessionCount} total +- Topics by status: ${topicBreakdown} +- Available agents: ${agentNames} +- Default agent: ${config.defaultAgent} +- Workspace base directory: ${config.workspace.baseDir} + +## Action Playbook + +### Create Session +- The workspace is the project directory where the agent will work (read, write, execute code). It is NOT the base directory β€” it should be a specific project folder like \`~/code/my-project\` or \`${config.workspace.baseDir}/my-app\`. +- Ask which agent to use (if multiple are configured). Show available: ${agentNames} +- Ask which project directory to use as workspace. Suggest \`${config.workspace.baseDir}\` as the base, but explain the user can provide any path. +- Confirm before creating: show agent name + full workspace path. +- Create via: \`openacp api new \` + +### Check Status / List Sessions +- Run \`openacp api status\` for active sessions overview +- Run \`openacp api topics\` for full list with statuses +- Format the output nicely for the user + +### Cancel Session +- Run \`openacp api status\` to see what's active +- If 1 active session β†’ ask user to confirm β†’ \`openacp api cancel \` +- If multiple β†’ list them, ask user which one to cancel + +### Troubleshoot (Session Stuck, Errors) +- Run \`openacp api health\` + \`openacp api status\` to diagnose +- Small issue (stuck session) β†’ suggest cancel + create new +- Big issue (system-level) β†’ suggest restart, ask for confirmation first + +### Cleanup Old Sessions +- Run \`openacp api topics --status finished,error\` to see what can be cleaned +- Report the count, ask user to confirm +- Execute: \`openacp api cleanup --status \` + +### Configuration +- View: \`openacp api config\` +- Update: \`openacp api config set \` + +### Restart / Update +- Always ask for confirmation β€” these are disruptive actions +- Guide user: "Tap πŸ”„ Restart button or type /restart" + +### Toggle Dangerous Mode +- Run \`openacp api dangerous on|off\` +- Explain: dangerous mode auto-approves all permission requests β€” the agent can run any command without asking + +## CLI Commands Reference +\`\`\`bash +# Session management +openacp api status # List active sessions +openacp api session # Session detail +openacp api new # Create new session +openacp api send "prompt text" # Send prompt to session +openacp api cancel # Cancel session +openacp api dangerous on|off # Toggle dangerous mode + +# Topic management +openacp api topics # List all topics +openacp api topics --status finished,error +openacp api delete-topic # Delete topic +openacp api delete-topic --force # Force delete active +openacp api cleanup # Cleanup finished topics +openacp api cleanup --status finished,error + +# System +openacp api health # System health +openacp api config # Show config +openacp api config set # Update config +openacp api adapters # List adapters +openacp api tunnel # Tunnel status +openacp api notify "message" # Send notification +openacp api version # Daemon version +openacp api restart # Restart daemon +\`\`\` + +## Guidelines +- Run \`openacp api ...\` commands yourself for everything you can. Only guide users to Telegram buttons/commands when needed (e.g., creating sessions requires a Telegram topic). +- Destructive actions (cancel active session, restart, cleanup) β†’ always ask user to confirm first. +- Small/obvious issues (clearly stuck session with no activity) β†’ fix it and report back. +- Respond in the same language the user uses. +- Format responses for Telegram: use bold, code, keep it concise. +- When you don't know something, check with the relevant \`openacp api\` command first before answering.`; +} +``` + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `pnpm test -- src/__tests__/assistant-prompt.test.ts` +Expected: All 6 tests PASS + +- [ ] **Step 5: Build and verify** + +Run: `pnpm build` +Expected: Clean build + +- [ ] **Step 6: Commit** + +```bash +git add src/adapters/telegram/assistant.ts src/__tests__/assistant-prompt.test.ts +git commit -m "feat(assistant): rewrite system prompt with product context and action playbook" +``` + +--- + +### Task 5: Interactive Session Creation Flow + +Rewrite `handleNew()` to use an interactive button flow when called without full args (outside assistant topic). + +**Files:** +- Modify: `src/adapters/telegram/commands.ts:126-216` (handleNew function) +- Modify: `src/adapters/telegram/commands.ts:55-117` (setupMenuCallbacks β€” add new `m:new:*` callbacks) + +- [ ] **Step 1: Add PendingNewSession state and types** + +At the top of `commands.ts` (after imports, around line 9), add: + +```typescript +interface PendingNewSession { + agentName?: string; + workspace?: string; + step: "agent" | "workspace" | "workspace_input" | "confirm"; + messageId: number; + threadId?: number; + timer: ReturnType; +} + +const pendingNewSessions = new Map(); + +const PENDING_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes + +function cleanupPending(userId: number): void { + const pending = pendingNewSessions.get(userId); + if (pending) { + clearTimeout(pending.timer); + pendingNewSessions.delete(userId); + } +} +``` + +- [ ] **Step 2: Rewrite handleNew() for interactive flow** + +Replace the `handleNew` function. The new logic: +- **Full args provided** (`/new claude ~/code/project`) β†’ create directly (keep current behavior) +- **In assistant topic without full args** β†’ forward to assistant (keep current behavior) +- **Outside assistant topic without full args** β†’ start interactive flow + +```typescript +async function handleNew( + ctx: Context, + core: OpenACPCore, + chatId: number, + assistant?: AssistantContext, +): Promise { + const rawMatch = (ctx as Context & { match: unknown }).match; + const matchStr = typeof rawMatch === "string" ? rawMatch : ""; + const args = matchStr.split(" ").filter(Boolean); + const agentName = args[0]; + const workspace = args[1]; + + // Full args β†’ create directly + if (agentName && workspace) { + await createSessionDirect(ctx, core, chatId, agentName, workspace); + return; + } + + // In assistant topic β†’ forward to assistant for conversational handling + const currentThreadId = ctx.message?.message_thread_id; + if (assistant && currentThreadId === assistant.topicId) { + const assistantSession = assistant.getSession(); + if (assistantSession) { + const prompt = agentName + ? `User wants to create a new session with agent "${agentName}" but didn't specify a workspace. Ask them which project directory to use as workspace.` + : `User wants to create a new session. Guide them through choosing an agent and workspace (project directory).`; + await assistantSession.enqueuePrompt(prompt); + return; + } + } + + // Outside assistant topic β†’ interactive flow + const userId = ctx.from?.id; + if (!userId) return; + + const agents = core.agentManager.getAvailableAgents(); + const config = core.configManager.get(); + + // If agent provided or only 1 agent β†’ skip to workspace step + if (agentName || agents.length === 1) { + const selectedAgent = agentName || config.defaultAgent; + await startWorkspaceStep(ctx, core, chatId, userId, selectedAgent); + return; + } + + // Multiple agents β†’ show agent selection + const keyboard = new InlineKeyboard(); + for (const agent of agents) { + const label = agent.name === config.defaultAgent + ? `${agent.name} (default)` + : agent.name; + keyboard.text(label, `m:new:agent:${agent.name}`).row(); + } + + const msg = await ctx.reply( + `πŸ€– Choose an agent:`, + { parse_mode: "HTML", reply_markup: keyboard }, + ); + + cleanupPending(userId); + pendingNewSessions.set(userId, { + step: "agent", + messageId: msg.message_id, + threadId: currentThreadId, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} +``` + +- [ ] **Step 3: Add helper functions for the interactive flow** + +Add these functions after the `handleNew` function: + +```typescript +async function startWorkspaceStep( + ctx: Context, + core: OpenACPCore, + chatId: number, + userId: number, + agentName: string, +): Promise { + const config = core.configManager.get(); + const baseDir = config.workspace.baseDir; + + const keyboard = new InlineKeyboard() + .text(`πŸ“ Default (${baseDir})`, "m:new:ws:default") + .row() + .text("✏️ Custom path", "m:new:ws:custom"); + + const text = + `πŸ“ Choose workspace for ${escapeHtml(agentName)}:\n\n` + + `The workspace is the project directory where the agent will read, write, and execute code.`; + + let msg; + try { + // Try to edit the existing message + const pending = pendingNewSessions.get(userId); + if (pending?.messageId) { + await ctx.api.editMessageText(chatId, pending.messageId, text, { + parse_mode: "HTML", + reply_markup: keyboard, + }); + msg = { message_id: pending.messageId }; + } else { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + } catch { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + + cleanupPending(userId); + pendingNewSessions.set(userId, { + agentName, + step: "workspace", + messageId: msg.message_id, + threadId: ctx.message?.message_thread_id ?? (ctx.callbackQuery as any)?.message?.message_thread_id, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + +async function startConfirmStep( + ctx: Context, + chatId: number, + userId: number, + agentName: string, + workspace: string, +): Promise { + const keyboard = new InlineKeyboard() + .text("βœ… Create", "m:new:confirm") + .text("❌ Cancel", "m:new:cancel"); + + const text = + `βœ… Ready to create session?\n\n` + + `Agent: ${escapeHtml(agentName)}\n` + + `Workspace: ${escapeHtml(workspace)}`; + + let msg; + try { + const pending = pendingNewSessions.get(userId); + if (pending?.messageId) { + await ctx.api.editMessageText(chatId, pending.messageId, text, { + parse_mode: "HTML", + reply_markup: keyboard, + }); + msg = { message_id: pending.messageId }; + } else { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + } catch { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + + cleanupPending(userId); + pendingNewSessions.set(userId, { + agentName, + workspace, + step: "confirm", + messageId: msg.message_id, + threadId: ctx.message?.message_thread_id ?? (ctx.callbackQuery as any)?.message?.message_thread_id, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + +async function createSessionDirect( + ctx: Context, + core: OpenACPCore, + chatId: number, + agentName: string, + workspace: string, +): Promise { + log.info({ userId: ctx.from?.id, agentName, workspace }, "New session command (direct)"); + + let threadId: number | undefined; + try { + const topicName = `πŸ”„ New Session`; + threadId = await createSessionTopic(botFromCtx(ctx), chatId, topicName); + + await ctx.api.sendMessage(chatId, `⏳ Setting up session, please wait...`, { + message_thread_id: threadId, + parse_mode: "HTML", + }); + + const session = await core.handleNewSession("telegram", agentName, workspace); + session.threadId = String(threadId); + + await core.sessionManager.updateSessionPlatform(session.id, { topicId: threadId }); + + const finalName = `πŸ”„ ${session.agentName} β€” New Session`; + try { + await ctx.api.editForumTopic(chatId, threadId, { name: finalName }); + } catch { /* ignore rename failures */ } + + await ctx.api.sendMessage( + chatId, + `βœ… Session started\n` + + `Agent: ${escapeHtml(session.agentName)}\n` + + `Workspace: ${escapeHtml(session.workingDirectory)}\n\n` + + `This is your coding session β€” chat here to work with the agent.`, + { + message_thread_id: threadId, + parse_mode: "HTML", + reply_markup: buildDangerousModeKeyboard(session.id, false), + }, + ); + + session.warmup().catch((err) => log.error({ err }, "Warm-up error")); + } catch (err) { + log.error({ err }, "Session creation failed"); + if (threadId) { + try { await ctx.api.deleteForumTopic(chatId, threadId); } catch { /* ignore */ } + } + const message = err instanceof Error ? err.message : String(err); + await ctx.reply(`❌ ${escapeHtml(message)}`, { parse_mode: "HTML" }); + } +} +``` + +- [ ] **Step 4: Add new `m:new:*` callbacks inside setupMenuCallbacks** + +**IMPORTANT: Middleware ordering.** grammY processes callback handlers in registration order. The existing `bot.callbackQuery(/^m:/, ...)` in `setupMenuCallbacks` matches ALL `m:` prefixed callbacks. If `m:new:agent:*` handlers are registered AFTER this catch-all, they will never be reached. Therefore, the new `m:new:*` callbacks MUST be handled INSIDE the existing `setupMenuCallbacks` function. + +Modify `setupMenuCallbacks` to handle the new callbacks. Add these cases inside the existing `bot.callbackQuery(/^m:/, async (ctx) => { ... })` handler, BEFORE the switch statement (since switch only does exact matches and we need prefix matching for `m:new:agent:`): + +```typescript +export function setupMenuCallbacks( + bot: Bot, + core: OpenACPCore, + chatId: number, + systemTopicIds?: { notificationTopicId: number; assistantTopicId: number }, +): void { + bot.callbackQuery(/^m:/, async (ctx) => { + const data = ctx.callbackQuery.data; + try { + await ctx.answerCallbackQuery(); + } catch { + /* expired or network β€” ignore */ + } + + // --- New session interactive flow (prefix-based) --- + if (data.startsWith("m:new:agent:")) { + const agentName = data.replace("m:new:agent:", ""); + const userId = ctx.from?.id; + if (userId) await startWorkspaceStep(ctx, core, chatId, userId, agentName); + return; + } + if (data === "m:new:ws:default") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName) return; + const workspace = core.configManager.get().workspace.baseDir; + await startConfirmStep(ctx, chatId, userId, pending.agentName, workspace); + return; + } + if (data === "m:new:ws:custom") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName) return; + try { + await ctx.api.editMessageText( + chatId, + pending.messageId, + `✏️ Enter the full path to your project directory:\n\n` + + `Example: ~/code/my-project or /home/user/projects/app`, + { parse_mode: "HTML" }, + ); + } catch { + await ctx.reply( + `✏️ Enter the full path to your project directory:`, + { parse_mode: "HTML" }, + ); + } + clearTimeout(pending.timer); + pending.step = "workspace_input"; + pending.timer = setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS); + return; + } + if (data === "m:new:confirm") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName || !pending?.workspace) return; + cleanupPending(userId); + try { + await ctx.api.editMessageText(chatId, pending.messageId, `⏳ Creating session...`, { parse_mode: "HTML" }); + } catch { /* ignore */ } + await createSessionDirect(ctx, core, chatId, pending.agentName, pending.workspace); + return; + } + if (data === "m:new:cancel") { + const userId = ctx.from?.id; + if (userId) cleanupPending(userId); + try { + await ctx.editMessageText("❌ Session creation cancelled.", { parse_mode: "HTML" }); + } catch { /* ignore */ } + return; + } + + // --- Existing menu callbacks (exact match) --- + switch (data) { + case "m:new": + await handleNew(ctx, core, chatId); + break; + // ... rest of existing cases unchanged ... + } + }); +} +``` + +The key change: new `m:new:*` callbacks are `if/return` blocks BEFORE the existing `switch` statement, all inside the same `bot.callbackQuery(/^m:/, ...)` handler. No middleware ordering issues. + +- [ ] **Step 5: Export handleWorkspaceInput and pendingNewSessions for adapter wiring** + +Export a handler function and the pending map from `commands.ts`: + +```typescript +/** + * Check if a text message is a workspace path input for the interactive new session flow. + * Returns true if the message was handled (caller should not process further). + */ +export async function handlePendingWorkspaceInput( + ctx: Context, + chatId: number, +): Promise { + const userId = ctx.from?.id; + if (!userId) return false; + const pending = pendingNewSessions.get(userId); + if (pending?.step !== "workspace_input" || !ctx.message?.text) return false; + + const workspace = ctx.message.text.trim(); + if (!workspace || !pending.agentName) { + await ctx.reply("⚠️ Please enter a valid directory path.", { parse_mode: "HTML" }); + return true; + } + + await startConfirmStep(ctx, chatId, userId, pending.agentName, workspace); + return true; +} +``` + +In `adapter.ts`, import `handlePendingWorkspaceInput` from `./commands.js` and add it to the message routing. Find the section where text messages are routed (around line 364-412 in the `setupRoutes` method), and add this check BEFORE the assistant message routing: + +```typescript +// Check for pending workspace input from interactive /new flow +if (await handlePendingWorkspaceInput(ctx, this.telegramConfig.chatId)) { + return; +} +``` + +This should be placed after the security check and before the assistant topic / session topic routing logic. The exact location is inside `setupRoutes()` in the `bot.on("message:text", ...)` handler, before the `if (threadId === this.assistantTopicId)` check. + +- [ ] **Step 6: Build and verify** + +Run: `pnpm build` +Expected: Clean build + +- [ ] **Step 7: Run full test suite** + +Run: `pnpm test` +Expected: All tests pass + +- [ ] **Step 8: Commit** + +```bash +git add src/adapters/telegram/commands.ts src/adapters/telegram/adapter.ts +git commit -m "feat(new-session): interactive flow with agent and workspace selection" +``` + +--- + +### Task 6: Final Integration Test + +Verify all changes work together. + +**Files:** (no new changes β€” verification only) + +- [ ] **Step 1: Run full build** + +Run: `pnpm build` +Expected: Clean build, no TypeScript errors + +- [ ] **Step 2: Run full test suite** + +Run: `pnpm test` +Expected: All tests pass (including new welcome-message and assistant-prompt tests) + +- [ ] **Step 3: Review changes** + +Run: `git diff --stat HEAD~5` (or however many commits back) +Verify: +- `assistant.ts` has: `WelcomeContext`, `buildWelcomeMessage`, rewritten `buildAssistantSystemPrompt` +- `commands.ts` has: new `buildMenuKeyboard` (8 buttons, 4 rows), rewritten `handleHelp`, interactive `handleNew`, `m:new:*` callbacks inside `setupMenuCallbacks`, `pendingNewSessions`, `handlePendingWorkspaceInput` +- `adapter.ts` has: welcome message using `buildWelcomeMessage()`, `handlePendingWorkspaceInput` wired in message routing + +- [ ] **Step 4: Commit if any fixes were needed** + +Only if adjustments were required during verification. diff --git a/docs/superpowers/specs/2026-03-22-assistant-ux-redesign.md b/docs/superpowers/specs/2026-03-22-assistant-ux-redesign.md new file mode 100644 index 0000000..9cf4c24 --- /dev/null +++ b/docs/superpowers/specs/2026-03-22-assistant-ux-redesign.md @@ -0,0 +1,309 @@ +# Assistant UX Redesign + +## Summary + +Redesign the Telegram Assistant experience to be smarter, more user-friendly, and capable of guiding users through all OpenACP features. The assistant should be approachable for new users while remaining powerful for experienced ones. + +## Requirements + +- **Target users**: Both individual devs and small teams with non-tech members. Prioritize easy onboarding. +- **Error handling**: Hybrid β€” auto-fix small/obvious issues, ask confirmation before destructive actions. +- **Welcome**: Context-aware based on current session state (pure logic, no AI). +- **Menu**: Keep all feature buttons visible for discoverability, organize logically. Remove New Chat and Cancel. +- **Assistant behavior**: Self-execute via `openacp api ...` when possible, guide user for Telegram-only actions. +- **Language**: Auto-detect, respond in user's language. +- **Startup speed**: Welcome message is static/logic-based. AI assistant spawns in background, does not block startup. + +## Design + +### 1. Welcome Message (Context-Aware, No AI) + +Replace the current fixed welcome message with `buildWelcomeMessage(ctx: WelcomeContext)` β€” a pure logic function that generates different messages based on state. + +**Interface:** + +```typescript +interface WelcomeContext { + activeCount: number; // sessions with status "active" or "initializing" + errorCount: number; // sessions with status "error" + totalCount: number; // all session records + agents: string[]; // from agentManager.getAvailableAgents() (not config.agents) + defaultAgent: string; // from config.defaultAgent +} +``` + +**Variant selection logic (evaluated top to bottom, first match wins):** + +1. `totalCount === 0` β†’ **No sessions variant** +2. `errorCount > 0` β†’ **Has errors variant** (show active + errors + total) +3. `activeCount > 0` β†’ **Has active variant** (show active + total) +4. Fallback β†’ **Has active variant** with `activeCount = 0` + +**Variant templates:** + +**No sessions (totalCount === 0):** +``` +πŸ‘‹ OpenACP is ready! + +No sessions yet. Tap πŸ†• New Session to start, or ask me anything! +``` + +**Has active sessions (activeCount > 0, errorCount === 0):** +``` +πŸ‘‹ OpenACP is ready! + +πŸ“Š 2 active / 5 total +Agents: claude (default), codex +``` + +**Has error sessions (errorCount > 0):** +``` +πŸ‘‹ OpenACP is ready! + +πŸ“Š 1 active, 2 errors / 5 total +⚠️ 2 sessions have errors β€” ask me to check if you'd like. + +Agents: claude (default), codex +``` + +All variants include the menu keyboard below. Agent list always shown except in "no sessions" variant (less noise for first-time users). + +Startup flow unchanged: send welcome (static) β†’ spawn assistant session (background) β†’ no blocking. + +### 2. Menu Keyboard + +Remove New Chat and Cancel. Reorganize into logical groups β€” common actions first, admin second: + +``` +Row 1: πŸ†• New Session (m:new) πŸ“‹ Sessions (m:topics) +Row 2: πŸ“Š Status (m:status) πŸ€– Agents (m:agents) +Row 3: πŸ”— Integrate (m:integrate) ❓ Help (m:help) +Row 4: πŸ”„ Restart (m:restart) ⬆️ Update (m:update) +``` + +**Removed from menu:** +- `πŸ’¬ New Chat` (`m:newchat`) β€” rarely used from assistant topic, `/newchat` still works as command +- `β›” Cancel` (`m:cancel`) β€” only meaningful inside session topics, user can ask assistant to cancel + +Callback handling: remove `m:newchat` and `m:cancel` cases from `setupMenuCallbacks()`. Keep all cleanup-related callbacks (`m:cleanup:*`) β€” they are triggered from the Sessions list (handleTopics), not from the top-level menu. + +### 3. Session Creation Flow (Redesign) + +The current `/new` command is confusing β€” it silently uses `baseDir` as workspace, but `baseDir` is just the **base directory** (e.g. `~/openacp-workspace`), not a specific project folder. Users don't understand where the agent will work. + +#### Key concept + +**Workspace = the project directory the agent works in.** Not the base dir. For example: `~/openacp-workspace/my-app` or `~/code/my-project`. The agent reads, writes, and executes code inside this directory. + +#### Flow: `/new` from assistant topic (no args or missing args) + +Forward to AI assistant for conversational handling. The assistant guides: + +1. Ask which agent (if multiple configured) β€” or skip if only one +2. Explain workspace concept: "Which project directory should the agent work in?" +3. Suggest the base dir as default, but make clear user can provide any path +4. Confirm before creating: "Creating session with **claude** at `~/code/my-project` β€” OK?" +5. Create via `openacp api new ` + +This is already partially implemented (handleNew forwards to assistant when args are missing). The improvement is in the system prompt β€” give the assistant better guidance on how to walk users through this. + +#### Flow: `/new` from outside assistant topic or menu button (no args) + +Interactive button-based flow: + +**Step 1 β€” Agent selection** (skip if only 1 agent): +``` +πŸ€– Choose an agent: +[claude (default)] [codex] +``` +Callbacks: `m:new:agent:` + +**Step 2 β€” Workspace selection:** +``` +πŸ“ Choose workspace for : + +The workspace is the project directory where the agent will read, write, and execute code. + +[πŸ“ Default (~/openacp-workspace)] [✏️ Custom path] +``` +- "Default" callback: `m:new:ws:default` β†’ uses `config.workspace.baseDir` +- "Custom path" callback: `m:new:ws:custom` β†’ bot replies "Enter the full path to your project directory:" and waits for next text message + +**Step 3 β€” Confirmation:** +``` +βœ… Ready to create session? + +Agent: claude +Workspace: ~/code/my-project + +[βœ… Create] [❌ Cancel] +``` +Callbacks: `m:new:confirm`, `m:new:cancel` + +On confirm β†’ create session (same logic as current handleNew with both args provided). + +#### Flow: `/new ` (full args) + +Skip interactive flow. Show confirmation message with details, then create directly. Same as current behavior but add a brief confirmation message in the new topic: + +``` +βœ… Session started +Agent: claude +Workspace: ~/code/my-project + +This is your coding session β€” chat here to work with the agent. +``` + +#### State management for interactive flow + +Use a simple in-memory map to track pending session creation state per user: + +```typescript +interface PendingNewSession { + agentName?: string; + workspace?: string; + step: 'agent' | 'workspace' | 'workspace_input' | 'confirm'; + messageId: number; // to edit the interactive message +} + +const pendingNewSessions = new Map(); // keyed by userId +``` + +Clean up after: confirm, cancel, or timeout (5 minutes). + +#### Files changed (additional) + +| File | Change | +|------|--------| +| `src/adapters/telegram/commands.ts` | Rewrite `handleNew()` with interactive flow, add new callbacks (`m:new:agent:*`, `m:new:ws:*`, `m:new:confirm`, `m:new:cancel`), add `pendingNewSessions` state | + +### 4. Assistant System Prompt (Complete Rewrite) + +Rewrite `buildAssistantSystemPrompt()` with these sections: + +#### 4.1 Identity & Product Context + +Tell the assistant what OpenACP is and who uses it: + +``` +You are the OpenACP Assistant β€” a helpful guide for managing AI coding sessions. + +OpenACP bridges messaging platforms (like Telegram) to AI coding agents (like Claude Code) +via the Agent Client Protocol (ACP). Users chat here, and their messages are routed to +AI agents that can read, write, and execute code in real workspaces. + +Each session runs in its own Telegram topic. You help users create sessions, monitor them, +troubleshoot issues, and manage the system. +``` + +#### 4.2 Current State (Dynamic) + +Same dynamic data as current β€” sessions, agents, workspace. Keep as-is. + +#### 4.3 Action Playbook + +Structured "when user says X β†’ do Y" with concrete examples: + +**Create session:** +- Explain that workspace = the project directory the agent will work in +- Ask which agent (if multiple configured), then which workspace (full path) +- Run `openacp api new ` to create the session +- Note: creating sessions via API is preferred because the assistant can guide through the full flow conversationally + +**Check status / list sessions:** +- Self-execute: `openacp api status`, `openacp api topics` +- Respond with formatted data + +**Cancel session:** +- Self-execute: `openacp api status` to see active sessions +- If 1 active β†’ ask confirm β†’ `openacp api cancel ` +- If multiple β†’ list, ask user to pick + +**Troubleshoot (session stuck, errors):** +- Self-execute: `openacp api health` + `openacp api status` +- Diagnose the problem +- Small issue (stuck session) β†’ suggest cancel + create new +- Big issue (system problem) β†’ suggest restart, ask confirm + +**Cleanup:** +- Self-execute: `openacp api topics --status finished,error` +- Report count, ask confirm +- Execute: `openacp api cleanup --status ` + +**Config:** +- Self-execute: `openacp api config` (view), `openacp api config set ` (update) + +**Restart / Update:** +- Always ask confirmation (destructive) +- Guide: "Tap πŸ”„ Restart or type /restart" + +**Toggle dangerous mode:** +- Self-execute: `openacp api dangerous on|off` +- Explain what it does if user seems unsure + +#### 4.4 Guidelines + +- Self-execute `openacp api ...` for everything you can. Only guide user to Telegram actions when needed (creating sessions, typing in topics). +- Destructive actions (cancel active session, restart, cleanup) β†’ always confirm first. +- Small/obvious fixes (cancel a clearly stuck session) β†’ do it, report back. +- Respond in the same language the user uses. +- Format for Telegram: bold, code blocks, concise. +- When creating sessions, guide through: agent selection β†’ workspace β†’ confirm. + +#### 4.5 Available Commands Reference + +Keep the current CLI command reference (`openacp api ...`) for the assistant to use. Remove the separate "Session Management Commands" section (Telegram bot commands like `/new`, `/cancel`) from the prompt β€” the playbook entries already contain the relevant Telegram commands where needed (e.g., "type `/new `" in the Create Session playbook entry). + +**Note on self-execution:** The assistant can run `openacp api ...` commands because the adapter already auto-approves permission requests containing "openacp" (existing behavior in adapter.ts). This spec does not change that behavior. + +### 5. Help Text (Use-Case Grouped) + +Rewrite `handleHelp()` to group commands by use case instead of flat list: + +``` +πŸ“– OpenACP Help + +πŸš€ Getting Started + Tap πŸ†• New Session to start coding with AI. + Each session gets its own topic β€” chat there to work with the agent. + +πŸ’‘ Common Tasks + /new [agent] [workspace] β€” Create new session + /cancel β€” Cancel session (in session topic) + /status β€” Show session or system status + /sessions β€” List all sessions + /agents β€” List available agents + +βš™οΈ System + /restart β€” Restart OpenACP + /update β€” Update to latest version + /integrate β€” Manage agent integrations + /menu β€” Show action menu + +πŸ”’ Session Options + /enable_dangerous β€” Auto-approve permissions + /disable_dangerous β€” Restore permission prompts + /handoff β€” Continue session in terminal + +πŸ’¬ Need help? Just ask me in this topic! +``` + +### 6. Files Changed + +| File | Change | +|------|--------| +| `src/adapters/telegram/assistant.ts` | Rewrite `buildAssistantSystemPrompt()`, add `buildWelcomeMessage()` | +| `src/adapters/telegram/commands.ts` | Rewrite `buildMenuKeyboard()`, rewrite `handleHelp()`, rewrite `handleNew()` with interactive flow, add new callbacks (`m:new:agent:*`, `m:new:ws:*`, `m:new:confirm`, `m:new:cancel`), add `pendingNewSessions` state, remove `m:newchat` and `m:cancel` from `setupMenuCallbacks()` | +| `src/adapters/telegram/adapter.ts` | Use `buildWelcomeMessage()` instead of inline welcome logic | + +### 7. Backward Compatibility + +- `/newchat` command remains registered and functional β€” only removed from menu UI and help text +- `/cancel` command remains registered and functional β€” only removed from menu UI +- All other commands unchanged +- Startup flow unchanged +- Routing logic unchanged +- Menu callback prefixes unchanged for remaining buttons +- `m:newchat` and `m:cancel` callbacks can be safely removed (inline buttons are not bookmarkable) +- `STATIC_COMMANDS` array: keep `/newchat` and `/cancel` in the list so they still appear in Telegram's `/` autocomplete β€” users who know these commands can still use them +- Cleanup callbacks (`m:cleanup:*`) remain unchanged β€” they are triggered from Sessions list, not the top-level menu diff --git a/src/__tests__/assistant-prompt.test.ts b/src/__tests__/assistant-prompt.test.ts new file mode 100644 index 0000000..363491e --- /dev/null +++ b/src/__tests__/assistant-prompt.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect } from "vitest"; +import { buildAssistantSystemPrompt, type AssistantContext } from "../adapters/telegram/assistant.js"; + +function makeCtx(overrides?: Partial): AssistantContext { + return { + config: { + agents: { claude: { command: "claude", args: [] }, codex: { command: "codex", args: [] } }, + defaultAgent: "claude", + workspace: { baseDir: "~/openacp-workspace" }, + } as any, + activeSessionCount: 2, + totalSessionCount: 5, + topicSummary: [ + { status: "active", count: 2 }, + { status: "finished", count: 3 }, + ], + ...overrides, + }; +} + +describe("buildAssistantSystemPrompt", () => { + it("includes identity and product guide", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("OpenACP Assistant"); + expect(prompt).toContain("Product Reference"); + expect(prompt).toContain("AI coding agents"); + }); + + it("includes current state", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("Active sessions: 2"); + expect(prompt).toContain("claude"); + expect(prompt).toContain("codex"); + }); + + it("includes product guide with CLI commands and features", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("openacp api"); + expect(prompt).toContain("cancel"); + expect(prompt).toContain("cleanup"); + expect(prompt).toContain("Handoff"); + expect(prompt).toContain("Dangerous"); + }); + + it("includes guidelines about self-execution", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("NEVER show"); + expect(prompt).toContain("confirm"); + expect(prompt).toContain("same language"); + }); + + it("does not include old Telegram bot commands section", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).not.toContain("Session Management Commands"); + expect(prompt).not.toContain("These are Telegram bot commands"); + }); + + it("includes workspace and project folder explanation", () => { + const prompt = buildAssistantSystemPrompt(makeCtx()); + expect(prompt).toContain("workspace"); + expect(prompt).toContain("project folder"); + }); +}); diff --git a/src/__tests__/welcome-message.test.ts b/src/__tests__/welcome-message.test.ts new file mode 100644 index 0000000..fa1750f --- /dev/null +++ b/src/__tests__/welcome-message.test.ts @@ -0,0 +1,74 @@ +import { describe, it, expect } from "vitest"; +import { buildWelcomeMessage, type WelcomeContext } from "../adapters/telegram/assistant.js"; + +describe("buildWelcomeMessage", () => { + it("shows no-sessions variant when totalCount is 0", () => { + const ctx: WelcomeContext = { + activeCount: 0, + errorCount: 0, + totalCount: 0, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("OpenACP is ready"); + expect(msg).toContain("No sessions yet"); + expect(msg).not.toContain("Agents:"); + }); + + it("shows active variant when there are active sessions and no errors", () => { + const ctx: WelcomeContext = { + activeCount: 2, + errorCount: 0, + totalCount: 5, + agents: ["claude", "codex"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("2 active / 5 total"); + expect(msg).toContain("claude (default)"); + expect(msg).toContain("codex"); + expect(msg).not.toContain("errors"); + }); + + it("shows error variant when there are error sessions", () => { + const ctx: WelcomeContext = { + activeCount: 1, + errorCount: 2, + totalCount: 5, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("1 active"); + expect(msg).toContain("2 errors"); + expect(msg).toContain("5 total"); + expect(msg).toContain("ask me to check"); + }); + + it("shows fallback variant when all sessions are finished (0 active, 0 errors)", () => { + const ctx: WelcomeContext = { + activeCount: 0, + errorCount: 0, + totalCount: 3, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("0 active / 3 total"); + expect(msg).toContain("Agents:"); + }); + + it("errors variant takes priority over active variant", () => { + const ctx: WelcomeContext = { + activeCount: 3, + errorCount: 1, + totalCount: 10, + agents: ["claude"], + defaultAgent: "claude", + }; + const msg = buildWelcomeMessage(ctx); + expect(msg).toContain("errors"); + expect(msg).toContain("ask me to check"); + }); +}); diff --git a/src/adapters/telegram/action-detect.ts b/src/adapters/telegram/action-detect.ts index f2352b5..1c14500 100644 --- a/src/adapters/telegram/action-detect.ts +++ b/src/adapters/telegram/action-detect.ts @@ -2,7 +2,7 @@ import { nanoid } from "nanoid"; import { InlineKeyboard } from "grammy"; import type { Bot } from "grammy"; import type { OpenACPCore } from "../../core/core.js"; -import { executeNewSession, executeCancelSession } from "./commands.js"; +import { executeNewSession, executeCancelSession, startInteractiveNewSession } from "./commands.js"; export interface DetectedAction { action: "new_session" | "cancel_session"; @@ -123,26 +123,38 @@ export function setupActionCallbacks( try { if (action.action === "new_session") { - await ctx.answerCallbackQuery({ text: "⏳ Creating session..." }); - const { threadId, firstMsgId } = await executeNewSession( - bot, - core, - chatId, - action.agent, - action.workspace, - ); - const topicLink = `https://t.me/c/${String(chatId).replace("-100", "")}/${firstMsgId ?? threadId}`; - const originalText = ctx.callbackQuery.message?.text ?? ""; - try { - await ctx.editMessageText( - originalText + - `\n\nβœ… Session created β†’ Go to topic`, - { parse_mode: "HTML" }, + // If both agent and workspace provided β†’ create directly + if (action.agent && action.workspace) { + await ctx.answerCallbackQuery({ text: "⏳ Creating session..." }); + const { threadId, firstMsgId } = await executeNewSession( + bot, + core, + chatId, + action.agent, + action.workspace, ); - } catch { - await ctx.editMessageReplyMarkup({ - reply_markup: { inline_keyboard: [] }, - }); + const topicLink = `https://t.me/c/${String(chatId).replace("-100", "")}/${firstMsgId ?? threadId}`; + const originalText = ctx.callbackQuery.message?.text ?? ""; + try { + await ctx.editMessageText( + originalText + + `\n\nβœ… Session created β†’ Go to topic`, + { parse_mode: "HTML" }, + ); + } catch { + await ctx.editMessageReplyMarkup({ + reply_markup: { inline_keyboard: [] }, + }); + } + } else { + // Missing workspace β†’ start interactive flow + await ctx.answerCallbackQuery(); + try { + await ctx.editMessageReplyMarkup({ + reply_markup: { inline_keyboard: [] }, + }); + } catch { /* best effort */ } + await startInteractiveNewSession(ctx, core, chatId, action.agent); } } else if (action.action === "cancel_session") { const assistantId = getAssistantSessionId(); diff --git a/src/adapters/telegram/adapter.ts b/src/adapters/telegram/adapter.ts index 6dd635b..5875787 100644 --- a/src/adapters/telegram/adapter.ts +++ b/src/adapters/telegram/adapter.ts @@ -24,6 +24,7 @@ import { setupIntegrateCallbacks, buildMenuKeyboard, buildSkillMessages, + handlePendingWorkspaceInput, STATIC_COMMANDS, } from "./commands.js"; import { PermissionHandler } from "./permissions.js"; @@ -31,6 +32,7 @@ import { spawnAssistant, handleAssistantMessage, redirectToAssistant, + buildWelcomeMessage, type SpawnAssistantResult, } from "./assistant.js"; import { @@ -235,6 +237,20 @@ export class TelegramAdapter extends ChannelAdapter { { topicId: this.assistantTopicId, getSession: () => this.assistantSession, + respawn: async () => { + if (this.assistantSession) { + await this.assistantSession.destroy(); + this.assistantSession = null; + } + const { session, ready } = await spawnAssistant( + this.core as OpenACPCore, + this, + this.assistantTopicId, + ); + this.assistantSession = session; + this.assistantInitializing = true; + ready.then(() => { this.assistantInitializing = false; }); + }, }, ); this.permissionHandler.setupCallbackHandler(); @@ -304,19 +320,15 @@ export class TelegramAdapter extends ChannelAdapter { try { const config = this.core.configManager.get(); const agents = this.core.agentManager.getAvailableAgents(); - const agentList = agents - .map((a) => `${escapeHtml(a.name)}${a.name === config.defaultAgent ? " (default)" : ""}`) - .join(", "); - const workspace = escapeHtml(config.workspace.baseDir); const allRecords = this.core.sessionManager.listRecords(); - const activeCount = allRecords.filter(r => r.status === 'active' || r.status === 'initializing').length; - const welcomeText = - `πŸ‘‹ OpenACP Assistant is online.\n\n` + - `Available agents: ${agentList}\n` + - `Workspace: ${workspace}\n` + - `Sessions: ${activeCount} active / ${allRecords.length} total\n\n` + - `Select an action:`; + const welcomeText = buildWelcomeMessage({ + activeCount: allRecords.filter(r => r.status === 'active' || r.status === 'initializing').length, + errorCount: allRecords.filter(r => r.status === 'error').length, + totalCount: allRecords.length, + agents: agents.map(a => a.name), + defaultAgent: config.defaultAgent, + }); await this.bot.api.sendMessage(this.telegramConfig.chatId, welcomeText, { message_thread_id: this.assistantTopicId, @@ -365,6 +377,11 @@ export class TelegramAdapter extends ChannelAdapter { this.bot.on("message:text", async (ctx) => { const threadId = ctx.message.message_thread_id; + // Check for pending workspace input from interactive /new flow + if (await handlePendingWorkspaceInput(ctx, this.core, this.telegramConfig.chatId, this.assistantTopicId)) { + return; + } + // General topic or no thread β†’ redirect to assistant if (!threadId) { const html = redirectToAssistant( @@ -427,6 +444,10 @@ export class TelegramAdapter extends ChannelAdapter { ); if (!session) return; const threadId = Number(session.threadId); + if (!threadId || isNaN(threadId)) { + log.warn({ sessionId, threadId: session.threadId }, "Session has no valid threadId, skipping message"); + return; + } switch (content.type) { case "thought": { diff --git a/src/adapters/telegram/assistant.ts b/src/adapters/telegram/assistant.ts index e2f2788..3963ca4 100644 --- a/src/adapters/telegram/assistant.ts +++ b/src/adapters/telegram/assistant.ts @@ -1,5 +1,6 @@ import type { OpenACPCore, ChannelAdapter, Config, Session } from "../../core/index.js"; import { createChildLogger } from "../../core/log.js"; +import { PRODUCT_GUIDE } from "../../product-guide.js"; const log = createChildLogger({ module: "telegram-assistant" }); export type SpawnAssistantResult = { @@ -64,53 +65,119 @@ export interface AssistantContext { topicSummary: { status: string; count: number }[] } -export function buildAssistantSystemPrompt(ctx: AssistantContext): string { - const { config, activeSessionCount, totalSessionCount, topicSummary } = ctx - const agentNames = Object.keys(config.agents).join(", ") - const topicBreakdown = topicSummary.map(s => `${s.status}: ${s.count}`).join(', ') || 'none' +export interface WelcomeContext { + activeCount: number; + errorCount: number; + totalCount: number; + agents: string[]; + defaultAgent: string; +} - return `You are the OpenACP Assistant. Help users manage their AI coding sessions and topics. +export function buildWelcomeMessage(ctx: WelcomeContext): string { + const { activeCount, errorCount, totalCount, agents, defaultAgent } = ctx; + + const agentList = agents + .map((a) => `${a}${a === defaultAgent ? " (default)" : ""}`) + .join(", "); + + // Variant 1: No sessions + if (totalCount === 0) { + return `πŸ‘‹ OpenACP is ready!\n\nNo sessions yet. Tap πŸ†• New Session to start, or ask me anything!`; + } + + // Variant 2: Has errors + if (errorCount > 0) { + return ( + `πŸ‘‹ OpenACP is ready!\n\n` + + `πŸ“Š ${activeCount} active, ${errorCount} errors / ${totalCount} total\n` + + `⚠️ ${errorCount} session${errorCount > 1 ? "s have" : " has"} errors β€” ask me to check if you'd like.\n\n` + + `Agents: ${agentList}` + ); + } + + // Variant 3/4: Has active or fallback + return ( + `πŸ‘‹ OpenACP is ready!\n\n` + + `πŸ“Š ${activeCount} active / ${totalCount} total\n` + + `Agents: ${agentList}` + ); +} + +export function buildAssistantSystemPrompt(ctx: AssistantContext): string { + const { config, activeSessionCount, totalSessionCount, topicSummary } = ctx; + const agentNames = Object.keys(config.agents).join(", "); + const topicBreakdown = + topicSummary.map((s) => `${s.status}: ${s.count}`).join(", ") || "none"; + + return `You are the OpenACP Assistant β€” a helpful guide for managing AI coding sessions. ## Current State - Active sessions: ${activeSessionCount} / ${totalSessionCount} total - Topics by status: ${topicBreakdown} - Available agents: ${agentNames} - Default agent: ${config.defaultAgent} -- Workspace base: ${config.workspace.baseDir} +- Workspace base directory: ${config.workspace.baseDir} -## Session Management Commands -These are Telegram bot commands (type directly in chat): -- /new [agent] [workspace] β€” Create new session -- /newchat β€” New chat with same agent & workspace -- /cancel β€” Cancel current session -- /status β€” Show status -- /agents β€” List agents -- /help β€” Show help +## Action Playbook -## Management Commands (via CLI) -You have access to bash. Use these commands to manage OpenACP: +### Create Session +- The workspace is the project directory where the agent will work (read, write, execute code). It is NOT the base directory β€” it should be a specific project folder like \`~/code/my-project\` or \`${config.workspace.baseDir}/my-app\`. +- Ask which agent to use (if multiple are configured). Show available: ${agentNames} +- Ask which project directory to use as workspace. Suggest \`${config.workspace.baseDir}\` as the base, but explain the user can provide any path. +- Confirm before creating: show agent name + full workspace path. +- Create via: \`openacp api new \` -### Session management +### Check Status / List Sessions +- Run \`openacp api status\` for active sessions overview +- Run \`openacp api topics\` for full list with statuses +- Format the output nicely for the user + +### Cancel Session +- Run \`openacp api status\` to see what's active +- If 1 active session β†’ ask user to confirm β†’ \`openacp api cancel \` +- If multiple β†’ list them, ask user which one to cancel + +### Troubleshoot (Session Stuck, Errors) +- Run \`openacp api health\` + \`openacp api status\` to diagnose +- Small issue (stuck session) β†’ suggest cancel + create new +- Big issue (system-level) β†’ suggest restart, ask for confirmation first + +### Cleanup Old Sessions +- Run \`openacp api topics --status finished,error\` to see what can be cleaned +- Report the count, ask user to confirm +- Execute: \`openacp api cleanup --status \` + +### Configuration +- View: \`openacp api config\` +- Update: \`openacp api config set \` + +### Restart / Update +- Always ask for confirmation β€” these are disruptive actions +- Guide user: "Tap πŸ”„ Restart button or type /restart" + +### Toggle Dangerous Mode +- Run \`openacp api dangerous on|off\` +- Explain: dangerous mode auto-approves all permission requests β€” the agent can run any command without asking + +## CLI Commands Reference \`\`\`bash +# Session management openacp api status # List active sessions openacp api session # Session detail +openacp api new # Create new session openacp api send "prompt text" # Send prompt to session openacp api cancel # Cancel session openacp api dangerous on|off # Toggle dangerous mode -\`\`\` -### Topic management -\`\`\`bash -openacp api topics # List topics +# Topic management +openacp api topics # List all topics openacp api topics --status finished,error openacp api delete-topic # Delete topic openacp api delete-topic --force # Force delete active openacp api cleanup # Cleanup finished topics openacp api cleanup --status finished,error -\`\`\` -### System -\`\`\`bash +# System openacp api health # System health openacp api config # Show config openacp api config set # Update config @@ -122,13 +189,18 @@ openacp api restart # Restart daemon \`\`\` ## Guidelines -- When a user asks about sessions or topics, run \`openacp api topics\` or \`openacp api status\` to get current data. -- When deleting: if the session is active/initializing, warn the user first. Only use --force if they confirm. -- Use \`openacp api health\` to check system status. -- Use \`openacp api config\` to check configuration, \`openacp api config set\` to update values. -- Format responses nicely for Telegram (use bold, code blocks). -- Be concise and helpful. Respond in the same language the user uses. -- When creating sessions, guide through: agent selection β†’ workspace β†’ confirm.` +- NEVER show \`openacp api ...\` commands to users. These are internal tools for YOU to run silently. Users should only see natural language responses and results. +- Run \`openacp api ...\` commands yourself for everything you can. Only guide users to Telegram buttons/menu when needed (e.g., "Tap πŸ†• New Session" or "Go to the session topic to chat with the agent"). +- When creating sessions: guide user through agent + workspace choice conversationally, then run the command yourself. +- Destructive actions (cancel active session, restart, cleanup) β†’ always ask user to confirm first in natural language. +- Small/obvious issues (clearly stuck session with no activity) β†’ fix it and report back. +- Respond in the same language the user uses. +- Format responses for Telegram: use bold, code, keep it concise. +- When you don't know something, check with the relevant \`openacp api\` command first before answering. +- Talk to users like a helpful assistant, not a CLI manual. Example: "BαΊ‘n cΓ³ 2 session Δ‘ang chαΊ‘y. Muα»‘n xem chi tiαΊΏt khΓ΄ng?" instead of listing commands. + +## Product Reference +${PRODUCT_GUIDE}`; } export async function handleAssistantMessage( diff --git a/src/adapters/telegram/commands.ts b/src/adapters/telegram/commands.ts index e43b3c4..1c7cf08 100644 --- a/src/adapters/telegram/commands.ts +++ b/src/adapters/telegram/commands.ts @@ -11,6 +11,28 @@ const log = createChildLogger({ module: "telegram-commands" }); interface AssistantContext { topicId: number; getSession: () => Session | null; + respawn: () => Promise; +} + +interface PendingNewSession { + agentName?: string; + workspace?: string; + step: "agent" | "workspace" | "workspace_input" | "confirm"; + messageId: number; + threadId?: number; + timer: ReturnType; +} + +const pendingNewSessions = new Map(); + +const PENDING_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes + +function cleanupPending(userId: number): void { + const pending = pendingNewSessions.get(userId); + if (pending) { + clearTimeout(pending.timer); + pendingNewSessions.delete(userId); + } } export function setupCommands( @@ -32,17 +54,15 @@ export function setupCommands( bot.command("restart", (ctx) => handleRestart(ctx, core)); bot.command("update", (ctx) => handleUpdate(ctx, core)); bot.command("integrate", (ctx) => handleIntegrate(ctx, core)); + bot.command("clear", (ctx) => handleClear(ctx, assistant)); } export function buildMenuKeyboard(): InlineKeyboard { return new InlineKeyboard() .text("πŸ†• New Session", "m:new") - .text("πŸ’¬ New Chat", "m:newchat") - .row() - .text("β›” Cancel", "m:cancel") - .text("πŸ“Š Status", "m:status") - .row() .text("πŸ“‹ Sessions", "m:topics") + .row() + .text("πŸ“Š Status", "m:status") .text("πŸ€– Agents", "m:agents") .row() .text("πŸ”— Integrate", "m:integrate") @@ -66,16 +86,81 @@ export function setupMenuCallbacks( /* expired or network β€” ignore */ } + // --- New session interactive flow (prefix-based) --- + if (data.startsWith("m:new:agent:")) { + const agentName = data.replace("m:new:agent:", ""); + const userId = ctx.from?.id; + if (userId) await startWorkspaceStep(ctx, core, chatId, userId, agentName); + return; + } + if (data === "m:new:ws:default") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName) return; + const workspace = core.configManager.get().workspace.baseDir; + await startConfirmStep(ctx, chatId, userId, pending.agentName, workspace); + return; + } + if (data === "m:new:ws:custom") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName) return; + try { + await ctx.api.editMessageText( + chatId, + pending.messageId, + `✏️ Enter your project path:\n\n` + + `Full path like ~/code/my-project\n` + + `Or just the folder name like my-project (will use ${core.configManager.get().workspace.baseDir}/)`, + { parse_mode: "HTML" }, + ); + } catch { + await ctx.reply( + `✏️ Enter your project path:`, + { parse_mode: "HTML" }, + ); + } + clearTimeout(pending.timer); + pending.step = "workspace_input"; + pending.timer = setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS); + return; + } + if (data === "m:new:confirm") { + const userId = ctx.from?.id; + if (!userId) return; + const pending = pendingNewSessions.get(userId); + if (!pending?.agentName || !pending?.workspace) return; + cleanupPending(userId); + const confirmMsgId = pending.messageId; + try { + await ctx.api.editMessageText(chatId, confirmMsgId, `⏳ Creating session...`, { parse_mode: "HTML" }); + } catch { /* ignore */ } + const resultThreadId = await createSessionDirect(ctx, core, chatId, pending.agentName, pending.workspace); + try { + if (resultThreadId) { + const link = buildDeepLink(chatId, resultThreadId); + await ctx.api.editMessageText(chatId, confirmMsgId, `βœ… Session created β†’ Open topic`, { parse_mode: "HTML" }); + } else { + await ctx.api.editMessageText(chatId, confirmMsgId, `❌ Session creation failed.`, { parse_mode: "HTML" }); + } + } catch { /* ignore */ } + return; + } + if (data === "m:new:cancel") { + const userId = ctx.from?.id; + if (userId) cleanupPending(userId); + try { + await ctx.editMessageText("❌ Session creation cancelled.", { parse_mode: "HTML" }); + } catch { /* ignore */ } + return; + } + switch (data) { case "m:new": await handleNew(ctx, core, chatId); break; - case "m:newchat": - await handleNewChat(ctx, core, chatId); - break; - case "m:cancel": - await handleCancel(ctx, core); - break; case "m:status": await handleStatus(ctx, core); break; @@ -135,62 +220,186 @@ async function handleNew( const agentName = args[0]; const workspace = args[1]; - // In assistant topic: if missing params, forward to assistant for conversational gathering + // Full args β†’ create directly + if (agentName && workspace) { + await createSessionDirect(ctx, core, chatId, agentName, workspace); + return; + } + + // In assistant topic β†’ forward to assistant for conversational handling const currentThreadId = ctx.message?.message_thread_id; - if ( - assistant && - currentThreadId === assistant.topicId && - (!agentName || !workspace) - ) { + if (assistant && currentThreadId === assistant.topicId) { const assistantSession = assistant.getSession(); if (assistantSession) { const prompt = agentName - ? `User wants to create a new session with agent "${agentName}" but didn't specify a workspace. Ask them which workspace to use.` - : `User wants to create a new session. Ask them which agent and workspace to use.`; + ? `User wants to create a new session with agent "${agentName}" but didn't specify a workspace. Ask them which project directory to use as workspace.` + : `User wants to create a new session. Guide them through choosing an agent and workspace (project directory).`; await assistantSession.enqueuePrompt(prompt); return; } } - log.info({ userId: ctx.from?.id, agentName }, "New session command"); + // Outside assistant topic β†’ interactive flow + const userId = ctx.from?.id; + if (!userId) return; + + const agents = core.agentManager.getAvailableAgents(); + const config = core.configManager.get(); + + // If agent provided or only 1 agent β†’ skip to workspace step + if (agentName || agents.length === 1) { + const selectedAgent = agentName || config.defaultAgent; + await startWorkspaceStep(ctx, core, chatId, userId, selectedAgent); + return; + } + + // Multiple agents β†’ show agent selection + const keyboard = new InlineKeyboard(); + for (const agent of agents) { + const label = agent.name === config.defaultAgent + ? `${agent.name} (default)` + : agent.name; + keyboard.text(label, `m:new:agent:${agent.name}`).row(); + } + + const msg = await ctx.reply( + `πŸ€– Choose an agent:`, + { parse_mode: "HTML", reply_markup: keyboard }, + ); + + cleanupPending(userId); + pendingNewSessions.set(userId, { + step: "agent", + messageId: msg.message_id, + threadId: currentThreadId, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + +async function startWorkspaceStep( + ctx: Context, + core: OpenACPCore, + chatId: number, + userId: number, + agentName: string, +): Promise { + const config = core.configManager.get(); + const baseDir = config.workspace.baseDir; + + const keyboard = new InlineKeyboard() + .text(`πŸ“ Use ${baseDir}`, "m:new:ws:default") + .row() + .text("✏️ Enter project path", "m:new:ws:custom"); + + const text = + `πŸ“ Where should ${escapeHtml(agentName)} work?\n\n` + + `Enter the path to your project folder β€” the agent will read, write, and run code there.\n\n` + + `Or use the default directory below:`; + + let msg; + try { + const pending = pendingNewSessions.get(userId); + if (pending?.messageId) { + await ctx.api.editMessageText(chatId, pending.messageId, text, { + parse_mode: "HTML", + reply_markup: keyboard, + }); + msg = { message_id: pending.messageId }; + } else { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + } catch { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + + cleanupPending(userId); + pendingNewSessions.set(userId, { + agentName, + step: "workspace", + messageId: msg.message_id, + threadId: ctx.message?.message_thread_id ?? (ctx.callbackQuery as any)?.message?.message_thread_id, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + +async function startConfirmStep( + ctx: Context, + chatId: number, + userId: number, + agentName: string, + workspace: string, +): Promise { + const keyboard = new InlineKeyboard() + .text("βœ… Create", "m:new:confirm") + .text("❌ Cancel", "m:new:cancel"); + + const text = + `βœ… Ready to create session?\n\n` + + `Agent: ${escapeHtml(agentName)}\n` + + `Project: ${escapeHtml(workspace)}`; + + let msg; + try { + const pending = pendingNewSessions.get(userId); + if (pending?.messageId) { + await ctx.api.editMessageText(chatId, pending.messageId, text, { + parse_mode: "HTML", + reply_markup: keyboard, + }); + msg = { message_id: pending.messageId }; + } else { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + } catch { + msg = await ctx.reply(text, { parse_mode: "HTML", reply_markup: keyboard }); + } + + cleanupPending(userId); + pendingNewSessions.set(userId, { + agentName, + workspace, + step: "confirm", + messageId: msg.message_id, + threadId: ctx.message?.message_thread_id ?? (ctx.callbackQuery as any)?.message?.message_thread_id, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + +async function createSessionDirect( + ctx: Context, + core: OpenACPCore, + chatId: number, + agentName: string, + workspace: string, +): Promise { + log.info({ userId: ctx.from?.id, agentName, workspace }, "New session command (direct)"); - // Create topic first so threadId is ready before session events fire let threadId: number | undefined; try { const topicName = `πŸ”„ New Session`; threadId = await createSessionTopic(botFromCtx(ctx), chatId, topicName); - // Let user know we're setting up (spawn + warm-up can take a while) await ctx.api.sendMessage(chatId, `⏳ Setting up session, please wait...`, { message_thread_id: threadId, parse_mode: "HTML", }); - const session = await core.handleNewSession( - "telegram", - agentName, - workspace, - ); + const session = await core.handleNewSession("telegram", agentName, workspace); session.threadId = String(threadId); - // Persist platform mapping - await core.sessionManager.updateSessionPlatform(session.id, { - topicId: threadId, - }); + await core.sessionManager.updateSessionPlatform(session.id, { topicId: threadId }); - // Rename topic with actual agent name const finalName = `πŸ”„ ${session.agentName} β€” New Session`; try { await ctx.api.editForumTopic(chatId, threadId, { name: finalName }); - } catch { - /* ignore rename failures */ - } + } catch { /* ignore rename failures */ } await ctx.api.sendMessage( chatId, - `βœ… Session started\n` + + `βœ… Session started\n` + `Agent: ${escapeHtml(session.agentName)}\n` + - `Workspace: ${escapeHtml(session.workingDirectory)}`, + `Workspace: ${escapeHtml(session.workingDirectory)}\n\n` + + `This is your coding session β€” chat here to work with the agent.`, { message_thread_id: threadId, parse_mode: "HTML", @@ -198,20 +407,16 @@ async function handleNew( }, ); - // Warm up model cache in background while user types session.warmup().catch((err) => log.error({ err }, "Warm-up error")); + return threadId ?? null; } catch (err) { log.error({ err }, "Session creation failed"); - // Clean up orphaned topic if session creation failed if (threadId) { - try { - await ctx.api.deleteForumTopic(chatId, threadId); - } catch { - /* ignore cleanup failures */ - } + try { await ctx.api.deleteForumTopic(chatId, threadId); } catch { /* ignore */ } } const message = err instanceof Error ? err.message : (typeof err === 'object' ? JSON.stringify(err) : String(err)); await ctx.reply(`❌ ${escapeHtml(message)}`, { parse_mode: "HTML" }); + return null; } } @@ -637,21 +842,54 @@ async function handleAgents(ctx: Context, core: OpenACPCore): Promise { async function handleHelp(ctx: Context): Promise { await ctx.reply( - `OpenACP Commands:\n\n` + + `πŸ“– OpenACP Help\n\n` + + `πŸš€ Getting Started\n` + + `Tap πŸ†• New Session to start coding with AI.\n` + + `Each session gets its own topic β€” chat there to work with the agent.\n\n` + + `πŸ’‘ Common Tasks\n` + `/new [agent] [workspace] β€” Create new session\n` + - `/newchat β€” New chat, same agent & workspace\n` + - `/cancel β€” Cancel current session\n` + - `/status β€” Show session/system status\n` + - `/agents β€” List available agents\n` + - `/menu β€” Show interactive menu\n` + + `/cancel β€” Cancel session (in session topic)\n` + + `/status β€” Show session or system status\n` + + `/sessions β€” List all sessions\n` + + `/agents β€” List available agents\n\n` + + `βš™οΈ System\n` + `/restart β€” Restart OpenACP\n` + - `/update β€” Update to latest version and restart\n` + - `/help β€” Show this help\n\n` + - `Or just chat in the πŸ€– Assistant topic for help!`, + `/update β€” Update to latest version\n` + + `/integrate β€” Manage agent integrations\n` + + `/menu β€” Show action menu\n\n` + + `πŸ”’ Session Options\n` + + `/enable_dangerous β€” Auto-approve permissions\n` + + `/disable_dangerous β€” Restore permission prompts\n` + + `/handoff β€” Continue session in terminal\n` + + `/clear β€” Clear assistant history\n\n` + + `πŸ’¬ Need help? Just ask me in this topic!`, { parse_mode: "HTML" }, ); } +async function handleClear(ctx: Context, assistant?: AssistantContext): Promise { + if (!assistant) { + await ctx.reply("⚠️ Assistant is not available.", { parse_mode: "HTML" }); + return; + } + + const threadId = ctx.message?.message_thread_id; + if (threadId !== assistant.topicId) { + await ctx.reply("ℹ️ /clear only works in the Assistant topic.", { parse_mode: "HTML" }); + return; + } + + await ctx.reply("πŸ”„ Clearing assistant history...", { parse_mode: "HTML" }); + + try { + await assistant.respawn(); + await ctx.reply("βœ… Assistant history cleared.", { parse_mode: "HTML" }); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + await ctx.reply(`❌ Failed to clear: ${message}`, { parse_mode: "HTML" }); + } +} + export function buildDangerousModeKeyboard(sessionId: string, enabled: boolean): InlineKeyboard { return new InlineKeyboard().text( enabled ? "πŸ” Disable Dangerous Mode" : "☠️ Enable Dangerous Mode", @@ -1055,6 +1293,90 @@ export function setupIntegrateCallbacks( }); } +/** + * Check if a text message is a workspace path input for the interactive new session flow. + * Returns true if the message was handled (caller should not process further). + */ +export async function handlePendingWorkspaceInput( + ctx: Context, + core: OpenACPCore, + chatId: number, + assistantTopicId?: number, +): Promise { + const userId = ctx.from?.id; + if (!userId) return false; + const pending = pendingNewSessions.get(userId); + if (!pending || !ctx.message?.text) return false; + // Accept text input at both "workspace" step (user types directly instead of pressing buttons) + // and "workspace_input" step (user pressed "Custom path" button) + if (pending.step !== "workspace_input" && pending.step !== "workspace") return false; + + // Only intercept in assistant topic (or no-thread/general) β€” never in session topics + const threadId = ctx.message.message_thread_id; + if (threadId && threadId !== assistantTopicId) return false; + + let workspace = ctx.message.text.trim(); + if (!workspace || !pending.agentName) { + await ctx.reply("⚠️ Please enter a valid directory path.", { parse_mode: "HTML" }); + return true; + } + + // Relative path (no / or ~ prefix) β†’ resolve against baseDir + if (!workspace.startsWith("/") && !workspace.startsWith("~")) { + const baseDir = core.configManager.get().workspace.baseDir; + workspace = `${baseDir.replace(/\/$/, "")}/${workspace}`; + } + + await startConfirmStep(ctx, chatId, userId, pending.agentName, workspace); + return true; +} + +/** + * Start the interactive new session flow (agent β†’ workspace β†’ confirm). + * Used by action-detect when workspace is not provided. + */ +export async function startInteractiveNewSession( + ctx: Context, + core: OpenACPCore, + chatId: number, + agentName?: string, +): Promise { + const userId = ctx.from?.id; + if (!userId) return; + + const agents = core.agentManager.getAvailableAgents(); + const config = core.configManager.get(); + + // If agent provided or only 1 agent β†’ skip to workspace step + if (agentName || agents.length === 1) { + const selectedAgent = agentName || config.defaultAgent; + await startWorkspaceStep(ctx, core, chatId, userId, selectedAgent); + return; + } + + // Multiple agents β†’ show agent selection + const keyboard = new InlineKeyboard(); + for (const agent of agents) { + const label = agent.name === config.defaultAgent + ? `${agent.name} (default)` + : agent.name; + keyboard.text(label, `m:new:agent:${agent.name}`).row(); + } + + const msg = await ctx.reply( + `πŸ€– Choose an agent:`, + { parse_mode: "HTML", reply_markup: keyboard }, + ); + + cleanupPending(userId); + pendingNewSessions.set(userId, { + step: "agent", + messageId: msg.message_id, + threadId: (ctx.callbackQuery as any)?.message?.message_thread_id, + timer: setTimeout(() => pendingNewSessions.delete(userId), PENDING_TIMEOUT_MS), + }); +} + export const STATIC_COMMANDS = [ { command: "new", description: "Create new session" }, { command: "newchat", description: "New chat, same agent & workspace" }, @@ -1068,6 +1390,7 @@ export const STATIC_COMMANDS = [ { command: "disable_dangerous", description: "Restore normal permission prompts (session only)" }, { command: "integrate", description: "Manage agent integrations" }, { command: "handoff", description: "Continue this session in your terminal" }, + { command: "clear", description: "Clear assistant history" }, { command: "restart", description: "Restart OpenACP" }, { command: "update", description: "Update to latest version and restart" }, ]; diff --git a/src/product-guide.ts b/src/product-guide.ts new file mode 100644 index 0000000..7e85b05 --- /dev/null +++ b/src/product-guide.ts @@ -0,0 +1,366 @@ +/** + * OpenACP Product Guide β€” comprehensive reference for the AI assistant. + * The assistant reads this at runtime to answer user questions about features. + */ +export const PRODUCT_GUIDE = ` +# OpenACP β€” Product Guide + +OpenACP lets you chat with AI coding agents (like Claude Code) through Telegram. +You type messages in Telegram, the agent reads/writes/runs code in your project folder, and results stream back in real time. + +--- + +## Quick Start + +1. Start OpenACP: \`openacp\` (or \`openacp start\` for background daemon) +2. Open your Telegram group β€” you'll see the Assistant topic +3. Tap πŸ†• New Session or type /new +4. Pick an agent and a project folder +5. Chat in the session topic β€” the agent works on your code + +--- + +## Core Concepts + +### Sessions +A session = one conversation with one AI agent working in one project folder. +Each session gets its own Telegram topic. Chat there to give instructions to the agent. + +### Agents +An agent is an AI coding tool (e.g., Claude Code). You can configure multiple agents. +The default agent is used when you don't specify one. + +### Project Folder (Workspace) +The directory where the agent reads, writes, and runs code. +When creating a session, you choose which folder the agent works in. +You can type a full path like \`~/code/my-project\` or just a name like \`my-project\` (it becomes \`/my-project\`). + +### System Topics +- **Assistant** β€” Always-on helper that can answer questions, create sessions, check status, troubleshoot +- **Notifications** β€” System alerts (permission requests, session errors, completions) + +--- + +## Creating Sessions + +### From menu +Tap πŸ†• New Session β†’ choose agent (if multiple) β†’ choose project folder β†’ confirm + +### From command +- \`/new\` β€” Interactive flow (asks agent + folder) +- \`/new claude ~/code/my-project\` β€” Create directly with specific agent and folder + +### From Assistant topic +Just ask: "Create a session for my-project with claude" β€” the assistant handles it + +### Quick new chat +\`/newchat\` in a session topic β€” creates new session with same agent and folder as current one + +--- + +## Working with Sessions + +### Chat +Type messages in the session topic. The agent responds with code changes, explanations, tool outputs. + +### What you see while the agent works +- **πŸ’­ Thinking indicator** β€” Shows when the agent is reasoning, with elapsed time +- **Text responses** β€” Streamed in real time, updated every few seconds +- **Tool calls** β€” When the agent runs commands or edits files, you see tool name, input, status, and output +- **πŸ“‹ Plan card** β€” Visual task progress with completed/in-progress/pending items and progress bar +- **"View File" / "View Diff" buttons** β€” Opens in browser with Monaco editor (requires tunnel) + +### Session lifecycle +1. **Creating** β€” Topic created, agent spawning +2. **Warming up** β€” Agent primes its cache (happens automatically, invisible to you) +3. **Active** β€” Ready for your messages +4. **Auto-naming** β€” After your first message, the session gets a descriptive name (agent summarizes in ~5 words). The topic title updates automatically. +5. **Finished/Error** β€” Session completed or hit an error + +### Agent skills +Some agents provide slash commands (e.g., /compact, /review). Available skills are pinned in the session topic. + +### Permission requests +When the agent wants to run a command, it asks for permission. +You see buttons: βœ… Allow, ❌ Reject (and sometimes "Always Allow"). +A notification also appears in the Notifications topic with a link to the request. + +### Dangerous mode +Auto-approves ALL permission requests β€” the agent runs any command without asking. +- Enable: \`/enable_dangerous\` or tap the ☠️ button in the session +- Disable: \`/disable_dangerous\` or tap the πŸ” button +- ⚠️ Use with caution β€” the agent can execute anything + +### Session timeout +Idle sessions are automatically cancelled after a configurable timeout (default: 60 minutes). +Configure via \`security.sessionTimeoutMinutes\` in config. + +--- + +## Session Transfer (Handoff) + +### Telegram β†’ Terminal +1. Type \`/handoff\` in a session topic +2. You get a command like \`claude --resume \` +3. Copy and run it in your terminal β€” the session continues there with full conversation history + +### Terminal β†’ Telegram +1. First time: run \`openacp integrate claude\` to install the handoff skill (one-time setup) +2. In Claude Code, use the /openacp:handoff slash command +3. The session appears as a new topic in Telegram and you can continue chatting there + +### How it works +- The agent session ID is shared between platforms +- Conversation history is preserved β€” pick up where you left off +- The agent that supports resume (e.g., Claude with \`--resume\`) handles the actual transfer + +--- + +## Managing Sessions + +### Status +- \`/status\` β€” Shows active sessions count and details +- Ask the Assistant: "What sessions are running?" + +### List all sessions +- \`/sessions\` β€” Shows all sessions with status (active, finished, error) + +### Cancel +- \`/cancel\` in a session topic β€” cancels that session +- Ask the Assistant: "Cancel the stuck session" + +### Cleanup +- From \`/sessions\` β†’ tap cleanup buttons (finished, errors, all) +- Ask the Assistant: "Clean up old sessions" + +--- + +## Assistant Topic + +The Assistant is an always-on AI helper in its own topic. It can: +- Answer questions about OpenACP +- Create sessions for you +- Check status and health +- Cancel sessions +- Clean up old sessions +- Troubleshoot issues +- Manage configuration + +Just chat naturally: "How do I create a session?", "What's the status?", "Something is stuck" + +### Clear history +\`/clear\` in the Assistant topic β€” resets the conversation + +--- + +## System Commands + +| Command | Where | What it does | +|---------|-------|-------------| +| \`/new [agent] [path]\` | Anywhere | Create new session | +| \`/newchat\` | Session topic | New session, same agent + folder | +| \`/cancel\` | Session topic | Cancel current session | +| \`/status\` | Anywhere | Show status | +| \`/sessions\` | Anywhere | List all sessions | +| \`/agents\` | Anywhere | List available agents | +| \`/enable_dangerous\` | Session topic | Auto-approve all permissions | +| \`/disable_dangerous\` | Session topic | Restore permission prompts | +| \`/handoff\` | Session topic | Transfer session to terminal | +| \`/clear\` | Assistant topic | Clear assistant history | +| \`/menu\` | Anywhere | Show action menu | +| \`/help\` | Anywhere | Show help | +| \`/restart\` | Anywhere | Restart OpenACP | +| \`/update\` | Anywhere | Update to latest version | +| \`/integrate\` | Anywhere | Manage agent integrations | + +--- + +## Menu Buttons + +| Button | Action | +|--------|--------| +| πŸ†• New Session | Create new session (interactive) | +| πŸ“‹ Sessions | List all sessions with cleanup options | +| πŸ“Š Status | Show active/total session count | +| πŸ€– Agents | List available agents | +| πŸ”— Integrate | Manage agent integrations | +| ❓ Help | Show help text | +| πŸ”„ Restart | Restart OpenACP | +| ⬆️ Update | Check and install updates | + +--- + +## CLI Commands + +### Server +- \`openacp\` β€” Start (uses configured mode: foreground or daemon) +- \`openacp start\` β€” Start as background daemon +- \`openacp stop\` β€” Stop daemon +- \`openacp status\` β€” Show daemon status +- \`openacp logs\` β€” Tail daemon logs +- \`openacp --foreground\` β€” Force foreground mode (useful for debugging or containers) + +### Auto-start (run on boot) +- macOS: installs a LaunchAgent in \`~/Library/LaunchAgents/\` +- Linux: installs a systemd user service in \`~/.config/systemd/user/\` +- Enabled automatically when you start the daemon. Remove with \`openacp stop\`. + +### Configuration +- \`openacp config\` β€” Interactive config editor +- \`openacp reset\` β€” Delete all data and start fresh + +### Plugins +- \`openacp install \` β€” Install adapter plugin (e.g., \`@openacp/adapter-discord\`) +- \`openacp uninstall \` β€” Remove adapter plugin +- \`openacp plugins\` β€” List installed plugins + +### Integration +- \`openacp integrate \` β€” Install agent integration (e.g., Claude handoff skill) +- \`openacp integrate --uninstall\` β€” Remove integration + +### API (requires running daemon) +\`openacp api \` β€” Interact with running daemon: + +| Command | Description | +|---------|-------------| +| \`status\` | List active sessions | +| \`session \` | Session details | +| \`new \` | Create session | +| \`send "text"\` | Send prompt | +| \`cancel \` | Cancel session | +| \`dangerous on/off\` | Toggle dangerous mode | +| \`topics [--status x,y]\` | List topics | +| \`delete-topic [--force]\` | Delete topic | +| \`cleanup [--status x,y]\` | Cleanup old topics | +| \`agents\` | List agents | +| \`health\` | System health | +| \`config\` | Show config | +| \`config set \` | Update config | +| \`adapters\` | List adapters | +| \`tunnel\` | Tunnel status | +| \`notify "message"\` | Send notification | +| \`version\` | Daemon version | +| \`restart\` | Restart daemon | + +--- + +## File Viewer (Tunnel) + +When tunnel is enabled, file edits and diffs get "View" buttons that open in your browser: +- **Monaco Editor** β€” Full VS Code editor with syntax highlighting +- **Diff viewer** β€” Side-by-side or inline comparison +- **Line highlighting** β€” Click lines to highlight +- Dark/light theme toggle + +### Setup +Enable in config: set \`tunnel.enabled\` to \`true\`. +Providers: Cloudflare (default, free), ngrok, bore, Tailscale Funnel. + +--- + +## Configuration + +Config file: \`~/.openacp/config.json\` + +### Telegram +- **telegram.botToken** β€” Your Telegram bot token +- **telegram.chatId** β€” Your Telegram supergroup ID + +### Agents +- **agents..command** β€” Agent executable path (e.g., \`claude\`, \`codex\`) +- **agents..args** β€” Arguments to pass to the agent command +- **agents..env** β€” Custom environment variables for the agent subprocess +- **defaultAgent** β€” Which agent to use by default + +### Workspace +- **workspace.baseDir** β€” Base directory for project folders (default: \`~/openacp-workspace\`) + +### Security +- **security.allowedUserIds** β€” Restrict who can use the bot (empty = everyone) +- **security.maxConcurrentSessions** β€” Max parallel sessions (default: 5) +- **security.sessionTimeoutMinutes** β€” Auto-cancel idle sessions (default: 60) + +### Tunnel / File Viewer +- **tunnel.enabled** β€” Enable file viewer tunnel +- **tunnel.provider** β€” Tunnel provider: cloudflare (default, free), ngrok, bore, tailscale +- **tunnel.port** β€” Local port for tunnel server (default: 3100) +- **tunnel.auth.enabled** β€” Enable authentication for tunnel URLs +- **tunnel.auth.token** β€” Auth token for tunnel access +- **tunnel.storeTtlMinutes** β€” How long viewer links stay cached (default: 60) + +### Logging +- **logging.level** β€” Log level: silent, debug, info, warn, error, fatal (default: info) +- **logging.logDir** β€” Log directory (default: \`~/.openacp/logs\`) +- **logging.maxFileSize** β€” Max log file size before rotation +- **logging.maxFiles** β€” Max number of rotated log files +- **logging.sessionLogRetentionDays** β€” Auto-delete old session logs (default: 30) + +### Data Retention +- **sessionStore.ttlDays** β€” How long session records persist (default: 30). Old records are cleaned up automatically. + +### Environment variables +Override config with env vars: +- \`OPENACP_TELEGRAM_BOT_TOKEN\` +- \`OPENACP_TELEGRAM_CHAT_ID\` +- \`OPENACP_DEFAULT_AGENT\` +- \`OPENACP_RUN_MODE\` β€” foreground or daemon +- \`OPENACP_API_PORT\` β€” API server port (default: 21420) +- \`OPENACP_TUNNEL_ENABLED\` +- \`OPENACP_TUNNEL_PORT\` +- \`OPENACP_TUNNEL_PROVIDER\` +- \`OPENACP_LOG_LEVEL\` +- \`OPENACP_LOG_DIR\` +- \`OPENACP_DEBUG\` β€” Sets log level to debug + +--- + +## Troubleshooting + +### Session stuck / not responding +- Check status: ask Assistant "Is anything stuck?" +- Cancel and create new: \`/cancel\` then \`/new\` +- Check system health: Assistant can run health check + +### Agent not found +- Check available agents: \`/agents\` +- Verify agent command is installed and in PATH +- Check config: agent command + args must be correct + +### Permission request not showing +- Check Notifications topic for the alert +- Try \`/enable_dangerous\` to auto-approve (if you trust the agent) + +### Session disappeared after restart +- Sessions persist across restarts +- Send a message in the old topic β€” it auto-resumes +- If topic was deleted, the session record may still exist in status + +### Bot not responding at all +- Check daemon: \`openacp status\` +- Check logs: \`openacp logs\` +- Restart: \`openacp start\` or \`/restart\` + +### Messages going to wrong topic +- Each session is bound to a specific Telegram topic +- If you see messages appearing in the Assistant topic instead of the session topic, try creating a new session + +### Viewing logs +- Session-specific logs: \`~/.openacp/logs/sessions/\` +- System logs: \`openacp logs\` to tail live +- Set \`OPENACP_DEBUG=true\` for verbose output + +--- + +## Data & Storage + +All data is stored in \`~/.openacp/\`: +- \`config.json\` β€” Configuration +- \`sessions/\` β€” Session records and state +- \`topics/\` β€” Topic-to-session mappings +- \`logs/\` β€” System and session logs +- \`plugins/\` β€” Installed adapter plugins +- \`openacp.pid\` β€” Daemon PID file + +Session records auto-cleanup: 30 days (configurable via \`sessionStore.ttlDays\`). +Session logs auto-cleanup: 30 days (configurable via \`logging.sessionLogRetentionDays\`). +`;