diff --git a/docs/superpowers/plans/2026-03-28-critical-code-fixes.md b/docs/superpowers/plans/2026-03-28-critical-code-fixes.md new file mode 100644 index 0000000..f81df23 --- /dev/null +++ b/docs/superpowers/plans/2026-03-28-critical-code-fixes.md @@ -0,0 +1,992 @@ +# Critical Code Fixes — 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:** Fix 20 critical and high-severity bugs identified in the codebase logic review (Batches 1-3). + +**Architecture:** Targeted fixes to existing files — no new modules. Each task is a small, independent patch (1-10 lines). Tests verify fix works. Existing tests must still pass. + +**Tech Stack:** TypeScript, Vitest, Node.js + +**Reference:** Full findings at `docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md` + +--- + +### Task 1: Guard processPrompt for finished state (C1) + +**Files:** +- Modify: `src/core/sessions/session.ts:171-181` +- Test: `src/core/sessions/__tests__/session-lifecycle.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/sessions/__tests__/session-lifecycle.test.ts`: + +```typescript +it("processPrompt silently returns if session is finished", async () => { + session.activate(); + session.finish("done"); + // Should not throw — silently returns + await session.enqueuePrompt("hello after finish"); + // Give the queue a tick to process + await new Promise((r) => setTimeout(r, 50)); + expect(mockAgent.prompt).not.toHaveBeenCalled(); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/sessions/__tests__/session-lifecycle.test.ts -t "finished"` +Expected: FAIL with "Invalid session transition: finished → active" + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/sessions/session.ts`, add guard at the top of `processPrompt`, after the warmup check (line 175), before `this.promptCount++` (line 177): + +```typescript + // Don't process prompts for finished sessions (queue may still drain) + if (this._status === "finished") return; +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/sessions/__tests__/session-lifecycle.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 2: Add cancelled to valid transitions from error (C2) + +**Files:** +- Modify: `src/core/sessions/session.ts:23` +- Test: `src/core/sessions/__tests__/session-state-machine.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/sessions/__tests__/session-state-machine.test.ts`: + +```typescript +it("allows error → cancelled transition", () => { + session.activate(); + session.fail("something broke"); + expect(() => session.markCancelled()).not.toThrow(); + expect(session.status).toBe("cancelled"); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/sessions/__tests__/session-state-machine.test.ts -t "error → cancelled"` +Expected: FAIL with "Invalid session transition: error → cancelled" + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/sessions/session.ts:23`, change: + +```typescript + error: new Set(["active"]), +``` + +to: + +```typescript + error: new Set(["active", "cancelled"]), +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/sessions/__tests__/session-state-machine.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 3: Wrap abortPrompt in try-catch in cancelSession (C13) + +**Files:** +- Modify: `src/core/sessions/session-manager.ts:118-124` +- Test: `src/core/sessions/__tests__/session-manager.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/sessions/__tests__/session-manager.test.ts`: + +```typescript +it("cancelSession completes even if abortPrompt throws", async () => { + const session = createMockSession("test-1"); + session.abortPrompt = vi.fn().mockRejectedValue(new Error("agent dead")); + manager.register(session); + await manager.cancelSession("test-1"); + expect(session.markCancelled).toHaveBeenCalled(); + expect(manager.getSession("test-1")).toBeUndefined(); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/sessions/__tests__/session-manager.test.ts -t "abortPrompt throws"` +Expected: FAIL with "agent dead" + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/sessions/session-manager.ts:118-124`, change: + +```typescript + async cancelSession(sessionId: string): Promise { + const session = this.sessions.get(sessionId); + if (session) { + await session.abortPrompt(); + session.markCancelled(); + this.sessions.delete(sessionId); + } +``` + +to: + +```typescript + async cancelSession(sessionId: string): Promise { + const session = this.sessions.get(sessionId); + if (session) { + try { + await session.abortPrompt(); + } catch { + // Agent may already be dead — continue with cleanup + } + session.markCancelled(); + this.sessions.delete(sessionId); + } +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/sessions/__tests__/session-manager.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 4: Remove thinking indicator on maxThinkingDuration (C5) + +**Files:** +- Modify: `src/core/adapter-primitives/primitives/activity-tracker.ts:74-76` +- Test: `src/core/adapter-primitives/__tests__/activity-tracker.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/adapter-primitives/__tests__/activity-tracker.test.ts`: + +```typescript +it("removes thinking indicator when maxThinkingDuration exceeded", async () => { + const removeThinking = vi.fn().mockResolvedValue(undefined); + const tracker = new ActivityTracker({ + thinkingRefreshInterval: 50, + maxThinkingDuration: 100, + thinkingDelay: 0, + }); + tracker.onThinkingStart("s1", { + showThinkingIndicator: vi.fn().mockResolvedValue(undefined), + updateThinkingIndicator: vi.fn().mockResolvedValue(undefined), + removeThinkingIndicator: removeThinking, + }); + // Wait for maxThinkingDuration + one refresh interval + await new Promise((r) => setTimeout(r, 200)); + expect(removeThinking).toHaveBeenCalled(); + tracker.destroy(); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/adapter-primitives/__tests__/activity-tracker.test.ts -t "maxThinkingDuration"` +Expected: FAIL — removeThinkingIndicator never called + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/adapter-primitives/primitives/activity-tracker.ts:74-76`, change: + +```typescript + if (Date.now() - state.startTime >= this.config.maxThinkingDuration) { + this.stopRefresh(state) + return + } +``` + +to: + +```typescript + if (Date.now() - state.startTime >= this.config.maxThinkingDuration) { + state.dismissed = true + this.stopRefresh(state) + state.callbacks.removeThinkingIndicator().catch(() => {}) + return + } +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/adapter-primitives/__tests__/activity-tracker.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 5: Move voiceMode "next" reset after successful prompt (F9) + +**Files:** +- Modify: `src/core/sessions/session.ts:201-206,233-236` +- Test: `src/core/sessions/__tests__/session-tts.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/sessions/__tests__/session-tts.test.ts`: + +```typescript +it("preserves voiceMode 'next' if prompt fails", async () => { + session.setVoiceMode("next"); + mockAgent.prompt.mockRejectedValueOnce(new Error("agent error")); + try { + await session.enqueuePrompt("test"); + await vi.waitFor(() => expect(mockAgent.prompt).toHaveBeenCalled()); + } catch {} + // voiceMode should still be "next" because the prompt failed + expect(session.voiceMode).toBe("next"); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/sessions/__tests__/session-tts.test.ts -t "preserves voiceMode"` +Expected: FAIL — voiceMode is "off" because it was reset before prompt + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/sessions/session.ts`, remove the early reset (lines 203-204): + +Change: + +```typescript + // TTS: inject prompt instruction + if (ttsActive) { + processed.text += TTS_PROMPT_INSTRUCTION; + if (this.voiceMode === "next") { + this.voiceMode = "off"; + } + } +``` + +to: + +```typescript + // TTS: inject prompt instruction + if (ttsActive) { + processed.text += TTS_PROMPT_INSTRUCTION; + } +``` + +Then after the successful prompt (around line 233, inside the try block after `const response = await this.agentInstance.prompt(...)`), add: + +```typescript + // Reset "next" voice mode only after successful prompt + if (ttsActive && this.voiceMode === "next") { + this.voiceMode = "off"; + } +``` + +Place this right after the existing `if (contextUsed) { this.pendingContext = null; }` block. + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/sessions/__tests__/session-tts.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 6: Unref permission gate timer (C8) + +**Files:** +- Modify: `src/core/sessions/permission-gate.ts:33-36` + +- [ ] **Step 1: Write minimal implementation** + +In `src/core/sessions/permission-gate.ts`, after the setTimeout (line 35), add unref: + +Change: + +```typescript + this.timeoutTimer = setTimeout(() => { + this.reject("Permission request timed out (no response received)"); + }, this.timeoutMs); +``` + +to: + +```typescript + this.timeoutTimer = setTimeout(() => { + this.reject("Permission request timed out (no response received)"); + }, this.timeoutMs); + if (typeof this.timeoutTimer === 'object' && 'unref' in this.timeoutTimer) { + (this.timeoutTimer as NodeJS.Timeout).unref(); + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test -- src/core/sessions/__tests__/permission-gate` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 7: Remove draft from map after finalize in shared DraftManager (C16) + +**Files:** +- Modify: `src/core/adapter-primitives/primitives/draft-manager.ts:96-100` +- Test: `src/core/adapter-primitives/__tests__/draft-manager.test.ts` + +- [ ] **Step 1: Write the failing test** + +Add to `src/core/adapter-primitives/__tests__/draft-manager.test.ts`: + +```typescript +it("removes draft from map after finalize", async () => { + const dm = new DraftManager(defaultConfig); + const draft = dm.getOrCreate("s1"); + draft.append("hello"); + await dm.finalize("s1"); + // getOrCreate should return a NEW draft, not the old finalized one + const newDraft = dm.getOrCreate("s1"); + expect(newDraft).not.toBe(draft); + expect(newDraft.isEmpty).toBe(true); + dm.destroyAll(); +}); +``` + +- [ ] **Step 2: Run test to verify it fails** + +Run: `pnpm test -- src/core/adapter-primitives/__tests__/draft-manager.test.ts -t "removes draft"` +Expected: FAIL — same draft instance returned with old content + +- [ ] **Step 3: Write minimal implementation** + +In `src/core/adapter-primitives/primitives/draft-manager.ts:96-100`, change: + +```typescript + async finalize(sessionId: string): Promise { + const draft = this.drafts.get(sessionId) + if (!draft) return + await draft.finalize() + } +``` + +to: + +```typescript + async finalize(sessionId: string): Promise { + const draft = this.drafts.get(sessionId) + if (!draft) return + await draft.finalize() + this.drafts.delete(sessionId) + } +``` + +- [ ] **Step 4: Run test to verify it passes** + +Run: `pnpm test -- src/core/adapter-primitives/__tests__/draft-manager.test.ts` +Expected: ALL PASS + +- [ ] **Step 5: Commit** + +--- + +### Task 8: Set session.threadId BEFORE createSession in lazy resume (C12) + +**Files:** +- Modify: `src/core/core.ts:303-311` (createSession params type) and `src/core/core.ts:313-323` (createSession body) and `src/core/core.ts:647-658` (lazyResume) + +- [ ] **Step 1: Write minimal implementation** + +In `src/core/core.ts:303-311`, add `threadId` to the params type: + +```typescript + async createSession(params: { + channelId: string; + agentName: string; + workingDirectory: string; + resumeAgentSessionId?: string; + existingSessionId?: string; + createThread?: boolean; + initialName?: string; + threadId?: string; + }): Promise { +``` + +Then in the body, after `const session = await this.sessionFactory.create(params);` (line 313) and BEFORE connecting the bridge (line 327), add: + +```typescript + // Set threadId early so agent events during bridge.connect() can find the thread + if (params.threadId) { + session.threadId = params.threadId; + } +``` + +Then in `lazyResume` (line 647-658), pass threadId in the createSession call: + +```typescript + const session = await this.createSession({ + channelId: record.channelId, + agentName: record.agentName, + workingDirectory: record.workingDir, + resumeAgentSessionId: record.agentSessionId, + existingSessionId: record.sessionId, + initialName: record.name, + threadId: message.threadId, + }); +``` + +Keep `session.threadId = message.threadId;` after the call as a no-op safety net. + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 9: Fix lazy resume — skip cancelled, fallback to fresh (F1+F2) + +**Files:** +- Modify: `src/core/core.ts:625-636,666-680` + +- [ ] **Step 1: Write minimal implementation** + +In `src/core/core.ts:625-636`, change the status check to also skip cancelled and finished sessions: + +Change: + +```typescript + // Don't resume errored sessions (cancelled sessions can still be resumed) + if (record.status === "error") { +``` + +to: + +```typescript + // Don't resume errored or cancelled sessions — spawn fresh instead + if (record.status === "error" || record.status === "cancelled") { +``` + +Then in the catch block (lines 666-680), add fallback to fresh session: + +Change the catch block to: + +```typescript + } catch (err) { + log.error({ err, record }, "Lazy resume failed, spawning fresh session"); + try { + const session = await this.createSession({ + channelId: record.channelId, + agentName: record.agentName, + workingDirectory: record.workingDir, + threadId: message.threadId, + }); + session.threadId = message.threadId; + session.activate(); + log.info({ sessionId: session.id }, "Fresh session created after resume failure"); + return session; + } catch (fallbackErr) { + log.error({ err: fallbackErr }, "Fresh session fallback also failed"); + const adapter = this.adapters.get(message.channelId); + if (adapter) { + try { + await adapter.sendMessage(message.threadId, { + type: "error", + text: `Failed to start session: ${fallbackErr instanceof Error ? fallbackErr.message : String(fallbackErr)}`, + }); + } catch { /* best effort */ } + } + return null; + } + } finally { +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 10: Backup corrupt sessions.json (C15) + +**Files:** +- Modify: `src/core/sessions/session-store.ts:136-138` + +- [ ] **Step 1: Write minimal implementation** + +In `src/core/sessions/session-store.ts:136-138`, change: + +```typescript + } catch (err) { + log.error({ err }, "Failed to load session store"); + } +``` + +to: + +```typescript + } catch (err) { + log.error({ err }, "Failed to load session store, backing up corrupt file"); + try { + fs.renameSync(this.filePath, `${this.filePath}.bak`); + } catch { /* best effort */ } + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test -- src/core/sessions/__tests__/session-store` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 11: Fix CLI api session field access (F19) + +**Files:** +- Modify: `src/cli/commands/api.ts:415-426` + +- [ ] **Step 1: Write minimal implementation** + +Change lines 415-426: + +```typescript + console.log(`Session details:`) + console.log(` ID : ${data.id}`) + console.log(` Agent : ${data.agent}`) + console.log(` Status : ${data.status}`) + console.log(` Name : ${data.name ?? '(none)'}`) + console.log(` Workspace : ${data.workspace}`) + console.log(` Created : ${data.createdAt}`) + console.log(` Dangerous : ${data.dangerous}`) + console.log(` Queue depth : ${data.queueDepth}`) + console.log(` Prompt active : ${data.promptActive}`) + console.log(` Channel : ${data.channelId ?? '(none)'}`) + console.log(` Thread : ${data.threadId ?? '(none)'}`) +``` + +to: + +```typescript + const s = (data.session ?? data) as Record + console.log(`Session details:`) + console.log(` ID : ${s.id}`) + console.log(` Agent : ${s.agent}`) + console.log(` Status : ${s.status}`) + console.log(` Name : ${s.name ?? '(none)'}`) + console.log(` Workspace : ${s.workspace}`) + console.log(` Created : ${s.createdAt}`) + console.log(` Dangerous : ${s.dangerousMode}`) + console.log(` Queue depth : ${s.queueDepth}`) + console.log(` Prompt active : ${s.promptRunning}`) + console.log(` Channel : ${s.channelId ?? '(none)'}`) + console.log(` Thread : ${s.threadId ?? '(none)'}`) +``` + +- [ ] **Step 2: Run build to verify no type errors** + +Run: `pnpm build` +Expected: SUCCESS + +- [ ] **Step 3: Commit** + +--- + +### Task 12: Fix CLI api health field access (F20) + +**Files:** +- Modify: `src/cli/commands/api.ts:459-471` + +- [ ] **Step 1: Write minimal implementation** + +Change lines 459-471: + +```typescript + const uptimeSeconds = typeof data.uptimeSeconds === 'number' ? data.uptimeSeconds : 0 + const hours = Math.floor(uptimeSeconds / 3600) + const minutes = Math.floor((uptimeSeconds % 3600) / 60) + const memoryBytes = typeof data.memoryUsage === 'number' ? data.memoryUsage : 0 + const memoryMB = (memoryBytes / 1024 / 1024).toFixed(1) + const sessions = data.sessions as Record ?? {} + console.log(`Status : ${data.status}`) + console.log(`Uptime : ${hours}h ${minutes}m`) + console.log(`Version : ${data.version}`) + console.log(`Memory : ${memoryMB} MB`) + console.log(`Sessions : ${sessions.active ?? 0} active / ${sessions.total ?? 0} total`) + console.log(`Adapters : ${data.adapters}`) + console.log(`Tunnel : ${data.tunnel}`) +``` + +to: + +```typescript + const uptimeMs = typeof data.uptime === 'number' ? data.uptime : 0 + const uptimeSeconds = Math.floor(uptimeMs / 1000) + const hours = Math.floor(uptimeSeconds / 3600) + const minutes = Math.floor((uptimeSeconds % 3600) / 60) + const mem = data.memory as Record | undefined + const memoryMB = mem ? (mem.rss / 1024 / 1024).toFixed(1) : '0.0' + const sessions = data.sessions as Record ?? {} + const tunnel = data.tunnel as Record | undefined + const tunnelStr = tunnel?.enabled ? `${tunnel.url}` : 'disabled' + const adapters = Array.isArray(data.adapters) ? data.adapters.join(', ') : String(data.adapters ?? 'none') + console.log(`Status : ${data.status}`) + console.log(`Uptime : ${hours}h ${minutes}m`) + console.log(`Version : ${data.version}`) + console.log(`Memory : ${memoryMB} MB`) + console.log(`Sessions : ${sessions.active ?? 0} active / ${sessions.total ?? 0} total`) + console.log(`Adapters : ${adapters}`) + console.log(`Tunnel : ${tunnelStr}`) +``` + +- [ ] **Step 2: Run build to verify no type errors** + +Run: `pnpm build` +Expected: SUCCESS + +- [ ] **Step 3: Commit** + +--- + +### Task 13: Use AgentCatalog in API sessions route (F21) + +**Files:** +- Modify: `src/plugins/api-server/routes/sessions.ts:112-115` + +- [ ] **Step 1: Write minimal implementation** + +Change lines 112-115: + +```typescript + const resolvedAgent = agent || config.defaultAgent; + const resolvedWorkspace = deps.core.configManager.resolveWorkspace( + workspace || config.agents[resolvedAgent]?.workingDirectory, + ); +``` + +to: + +```typescript + const resolvedAgent = agent || config.defaultAgent; + const agentDef = deps.core.agentCatalog?.resolve(resolvedAgent); + const resolvedWorkspace = deps.core.configManager.resolveWorkspace( + workspace || agentDef?.workingDirectory, + ); +``` + +- [ ] **Step 2: Run build to verify no type errors** + +Run: `pnpm build` +Expected: SUCCESS (if `agentCatalog` is accessible on core — check and add getter if needed) + +- [ ] **Step 3: Commit** + +--- + +### Task 14: Validate config before writing to disk (C3) + +**Files:** +- Modify: `src/core/config/config.ts:260-283` + +- [ ] **Step 1: Write minimal implementation** + +Change `save()` method to validate before writing: + +```typescript + async save( + updates: Record, + changePath?: string, + ): Promise { + const oldConfig = this.config ? structuredClone(this.config) : undefined; + // Read current file, merge updates + const raw = JSON.parse(fs.readFileSync(this.configPath, "utf-8")); + this.deepMerge(raw, updates); + // Validate BEFORE writing to disk + const result = ConfigSchema.safeParse(raw); + if (!result.success) { + log.error({ errors: result.error.issues }, 'Config validation failed, not saving'); + return; + } + // Write validated config to disk + fs.writeFileSync(this.configPath, JSON.stringify(raw, null, 2)); + this.config = result.data; + // Emit change event if path provided + if (changePath) { + const { getConfigValue } = await import("./config-registry.js"); + const value = getConfigValue(this.config, changePath); + const oldValue = oldConfig + ? getConfigValue(oldConfig, changePath) + : undefined; + this.emit("config:changed", { path: changePath, value, oldValue }); + } + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test -- src/__tests__/config` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 15: Close session logger file descriptors (C4) + +**Files:** +- Modify: `src/core/utils/log.ts:210` +- Modify: `src/core/sessions/session.ts:494-503` + +- [ ] **Step 1: Write minimal implementation** + +In `src/core/utils/log.ts`, add after `createSessionLogger` function (after line 210): + +```typescript +export function closeSessionLogger(logger: Logger): void { + const dest = (logger as any).__sessionDest + if (dest && typeof dest.destroy === 'function') { + dest.destroy() + } +} +``` + +In `src/core/sessions/session.ts`, import and call in `destroy()`: + +Add to imports at top: + +```typescript +import { createChildLogger, createSessionLogger, closeSessionLogger, type Logger } from "../utils/log.js"; +``` + +In `destroy()` method (line 494-503), add before the final line: + +```typescript + async destroy(): Promise { + this.log.info("Session destroyed"); + // Reject any pending permission promise so callers don't hang + if (this.permissionGate.isPending) { + this.permissionGate.reject("Session destroyed"); + } + // Clear queued prompts + this.queue.clear(); + await this.agentInstance.destroy(); + // Close session log file descriptor + closeSessionLogger(this.log); + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 16: Clean up spinner/logger on boot failure (C6) + +**Files:** +- Modify: `src/main.ts:270-272` + +- [ ] **Step 1: Write minimal implementation** + +Change lines 270-272: + +```typescript + } catch (err) { + log.error({ err }, 'Plugin boot failed') + } +``` + +to: + +```typescript + } catch (err) { + if (spinner) { + spinner.fail('Plugin boot failed') + spinner = undefined + } + unmuteLogger() + log.error({ err }, 'Plugin boot failed') + } +``` + +- [ ] **Step 2: Run build to verify no type errors** + +Run: `pnpm build` +Expected: SUCCESS + +- [ ] **Step 3: Commit** + +--- + +### Task 17: Catch sendMessage middleware errors (C9) + +**Files:** +- Modify: `src/core/sessions/session-bridge.ts:40-53` + +- [ ] **Step 1: Write minimal implementation** + +Wrap the entire `sendMessage` body in try-catch: + +```typescript + private async sendMessage(sessionId: string, message: ReturnType): Promise { + try { + const mw = this.deps.middlewareChain; + if (mw) { + const result = await mw.execute('message:outgoing', { sessionId, message }, async (m) => m); + if (!result) return; // blocked by middleware + this.adapter.sendMessage(sessionId, result.message).catch((err) => { + log.error({ err, sessionId }, "Failed to send message to adapter"); + }); + } else { + this.adapter.sendMessage(sessionId, message).catch((err) => { + log.error({ err, sessionId }, "Failed to send message to adapter"); + }); + } + } catch (err) { + log.error({ err, sessionId }, "Error in sendMessage middleware"); + } + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test -- src/core/sessions/__tests__/session-bridge` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 18: ToolCardState appendUsage — use scheduleFlush (C14) + +**Files:** +- Modify: `src/core/adapter-primitives/primitives/tool-card-state.ts:122-126` + +- [ ] **Step 1: Write minimal implementation** + +Change: + +```typescript + appendUsage(usage: UsageData): void { + if (this.finalized) return; + this.usage = usage; + this.flush(); + } +``` + +to: + +```typescript + appendUsage(usage: UsageData): void { + if (this.finalized) return; + this.usage = usage; + this.scheduleFlush(); + } +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test -- src/core/adapter-primitives/__tests__/tool-card-state` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 19: Node stream adapters — add close/cancel handlers (C11) + +**Files:** +- Modify: `src/core/utils/streams.ts:3-26` + +- [ ] **Step 1: Write minimal implementation** + +Change `nodeToWebWritable`: + +```typescript +export function nodeToWebWritable(nodeStream: NodeJS.WritableStream): WritableStream { + return new WritableStream({ + write(chunk) { + return new Promise((resolve, reject) => { + const ok = nodeStream.write(chunk); + if (ok) { resolve(); return; } + (nodeStream as any).once("drain", resolve); + (nodeStream as any).once("error", reject); + }); + }, + close() { + (nodeStream as any).end(); + }, + abort(reason) { + (nodeStream as any).destroy(reason instanceof Error ? reason : new Error(String(reason))); + }, + }); +} +``` + +Change `nodeToWebReadable`: + +```typescript +export function nodeToWebReadable(nodeStream: NodeJS.ReadableStream): ReadableStream { + return new ReadableStream({ + start(controller) { + nodeStream.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); + nodeStream.on("end", () => controller.close()); + nodeStream.on("error", (err) => controller.error(err)); + }, + cancel() { + (nodeStream as any).destroy(); + }, + }); +} +``` + +- [ ] **Step 2: Run existing tests** + +Run: `pnpm test` +Expected: ALL PASS + +- [ ] **Step 3: Commit** + +--- + +### Task 20: Final verification + +- [ ] **Step 1: Run full test suite** + +Run: `pnpm test` +Expected: ALL PASS + +- [ ] **Step 2: Run build** + +Run: `pnpm build` +Expected: SUCCESS + +- [ ] **Step 3: Verify no regressions** + +Run: `pnpm test -- --reporter=verbose 2>&1 | tail -20` +Expected: All test suites pass, no new failures diff --git a/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md b/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md new file mode 100644 index 0000000..4868870 --- /dev/null +++ b/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md @@ -0,0 +1,294 @@ +# Codebase Logic Review — Comprehensive Findings + +**Date:** 2026-03-28 +**Scope:** Feature specs vs implementation, code-level bugs, architecture review, test coverage +**Total issues:** 76 (19 feature bugs, 14 missing features, 19 code bugs, 5 architecture gaps, 19 test gaps) + +--- + +# 1. Feature Review (Spec vs Implementation) + +## 1.1 Session Management + +### Session Persistence (spec: 2026-03-20) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F1 | Cancelled sessions spawn fresh, not resume | **WRONG** — code resumes them | `core.ts:625-626` | Not tested | +| F2 | Resume failure falls back to fresh session | **WRONG** — returns null, drops message | `core.ts:668-679` | Not tested | +| | SessionRecord type | Correct | `session-store.ts:8-18` | Thorough | +| | JsonFileSessionStore (debounce, TTL, cleanup) | Correct | `session-store.ts` | Thorough | +| | Lazy resume lock per topic | Correct | `core.ts:607-611` | Not tested | +| | Auto-cleanup skips active/initializing | Correct | `session-store.ts:145` | Tested | + +### /archive Command (spec: 2026-03-23) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F3 | Archive keeps agent alive, recreates topic | **WRONG** — kills agent + deletes topic + removes record | `core.ts:189-232` | Tested (wrong behavior) | +| F4 | Archive recreates topic (delete old + create new + rewire) | **MISSING** — only deletes, no recreation | `adapter.ts:1358-1385` | -- | +| F5 | Archive validates session state (must be active) | **MISSING** — no status check | `session.ts:358-385` | Not tested | +| F6 | Archive detects non-session topic usage | **MISSING** — no topic type check | `session.ts:358-385` | Not tested | +| | Confirmation flow with `ar:` callbacks | Correct | `session.ts:371-384` | Tested | +| | `session.archiving` flag | Correct | `session.ts:56` | Not tested | + +### Context Resume /resume (spec: 2026-03-25) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F7 | Over-budget interactive selection (options + 60s timeout) | **MISSING** — silently truncates | `resume.ts:162-266` | Not tested | +| | ContextProvider interface | Correct | `context-provider.ts` | Tested | +| | ContextManager (register, build, cache) | Correct | `context-manager.ts` | Tested | +| | All 6 entry points (PR, branch, commit, checkpoint, session, latest) | Correct | `checkpoint-reader.ts` | Tested | +| | Conversation rebuild pipeline (parse, clean, build, mode) | Correct | `conversation-builder.ts` | Tested | +| | Context injection (first prompt only, survives warmup) | Correct | `session.ts:186-189` | Well tested | +| | Caching with 1h TTL | Correct | `context-cache.ts` | Tested | + +### Session Handoff (spec: 2026-03-22) +| | adoptSession() with full validation chain | Correct | `core.ts:393-525` | Barely tested | +| | /handoff command | Correct | Telegram commands | Not tested | +| | findByAgentSessionId() | Correct | `session-store.ts:75-80` | Tested | + +--- + +## 1.2 TTS / Speech + +### Speech Module (spec: 2026-03-23) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F8 | Lazy provider initialization | **WRONG** — GroqSTT eagerly constructed at boot | `speech/index.ts:155` | Not tested | +| | STTProvider/TTSProvider interfaces | Correct | `speech-types.ts` | Indirect | +| | SpeechService orchestrator | Correct | `speech-service.ts` | Tested | +| | Groq Whisper STT (API, errors) | Correct | `providers/groq.ts` | Tested | +| | STT flow (transcribe OGG, error fallback) | Correct | `session.ts:265-321` | Not tested | + +### TTS Feature (spec: 2026-03-24) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F9 | voiceMode "next" resets AFTER prompt, not before | **WRONG** — resets before prompt at line 203 | `session.ts:203-204` | Tested (wrong behavior) | +| F10 | `tts_strip` event to remove [TTS] block from streamed text | **MISSING** — block stays visible | -- | -- | +| | voiceMode states (off/next/on) | Correct | `session.ts:48` | Tested | +| | TTS_PROMPT_INSTRUCTION injection | Correct | `session.ts:14,196-206` | Tested | +| | Post-response TTS pipeline (accumulate, parse, synthesize) | Correct | `session.ts:208-360` | Tested | +| | 30s TTS timeout | Correct | `session.ts:340` | Not tested | + +### msedge-tts Extraction (spec: 2026-03-27) +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F11 | /tts command doesn't actually set voiceMode | **WRONG** — speech plugin /tts has no session access | `speech/index.ts:173-225` | Tested (wrong behavior) | +| F12 | ttsProvider config ignored, hardcoded to edge-tts | **WRONG** — config.ttsProvider never read | `speech/index.ts:147` | Not tested | +| | Plugin structure and registration | Correct | `built-in-plugins/msedge-tts-plugin/` | Tested | +| | unregisterTTSProvider() | Correct | `speech-service.ts:25-27` | Tested | +| | Auto-install flow | Correct | `speech/index.ts:193-216` | Tested | + +--- + +## 1.3 Activity Tracker (spec: 2026-03-20) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F13 | ThinkingIndicator dismiss() deletes message | **WRONG** — only clears state, message persists in chat | `activity.ts:59-63` | Tested (wrong behavior) | +| F14 | UsageMessage class (separate, delete on next prompt) | **MISSING** — no UsageMessage, usage folded into ToolCard | `activity.ts:313-318` | -- | +| F15 | PlanCard as separate message with 3.5s debounce | **CHANGED** — merged into ToolCard, 500ms debounce | `activity.ts:108-220` | Partial | +| | Plan status icons (completed/in_progress/pending) | Correct | `tool-card-state.ts` | Tested | + +--- + +## 1.4 Adapter Layer (spec: 2026-03-25) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F16 | MessagingAdapter composes shared primitives | **MISSING** — thin dispatch layer, no send/edit/enqueueSend | `messaging-adapter.ts` | -- | +| | IChannelAdapter interface | Correct | `channel.ts:18` | Conformance | +| | StreamAdapter | Correct | `stream-adapter.ts` | Not tested | +| | IRenderer/BaseRenderer/TelegramRenderer | Correct | `rendering/renderer.ts` | Not tested | +| | All shared primitives (SendQueue, Draft, ToolCallTracker, ActivityTracker) | Correct | `primitives/` | Tested | + +--- + +## 1.5 Skill Commands (spec: 2026-03-19) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F17 | Skill commands as inline keyboard buttons with `s:` callback | **WRONG** — plain text `/cmd`, no buttons | `menu.ts:90-109` | -- | +| | sendSkillCommands/cleanupSkillCommands | Correct | `adapter.ts:1243-1255` | Tested | +| | Static commands via setMyCommands() | Correct | `adapter.ts:239-241` | -- | +| | Pinned message per session | Correct | `skill-command-manager.ts:87-89` | Tested | + +--- + +## 1.6 Usage Tracking (spec: 2026-03-22) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F18 | UsageStore + UsageBudget + /usage command | **MISSING** — old code removed, new plugin never created | -- | -- | +| | usage:recorded event emission | Correct | `session-factory.ts:112` | Tested | +| | UsageRecord/UsageRecordEvent types | Correct | `types.ts:235-252` | -- | + +--- + +## 1.7 API / CLI (spec: 2026-03-21) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F19 | CLI `api session` reads wrong fields (no .session wrapper, wrong names) | **BUG** — all fields show `undefined` | `api.ts:416-426` | Not tested | +| F20 | CLI `api health` reads wrong fields (uptimeSeconds, memoryUsage) | **BUG** — shows zeros | `api.ts:459-462` | Not tested | +| F21 | POST /api/sessions uses deprecated config.agents[] | **BUG** — workspace always undefined after migration | `routes/sessions.ts:114` | Not tested | +| | All 11+ API endpoints | Correct | `routes/` | Router only | +| | Config redaction | Correct | `routes/config.ts:4-32` | Not tested | +| | Typo suggestions (suggestMatch) | Correct, 8 integration points | `cli/suggest.ts` | 13 tests | + +--- + +## 1.8 Plugin System (spec: 2026-03-26) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F22 | Settings validation against settingsSchema at boot | **MISSING** — validateSettings() exists but never called | `lifecycle-manager.ts:212-224` | Not tested | +| F23 | Legacy config stripping after migration | **MISSING** — old fields remain in config.json | `main.ts:398-477` | Not tested | +| | Plugin lifecycle hooks (install, configure, uninstall, migrate) | Correct | `types.ts:51-57` | Indirect | +| | SettingsAPI per-plugin persistence | Correct | `settings-manager.ts` | Thorough | +| | PluginRegistry (CRUD, enable/disable) | Correct | `plugin-registry.ts` | Thorough | +| | Boot with dependency order + migration | Correct | `lifecycle-manager.ts` | Tested | +| | MiddlewareChain (priority, timeout, circuit break) | Correct | `middleware-chain.ts` | 15 tests | + +--- + +## 1.9 Tunnel Service (specs: 2026-03-20, 2026-03-23) + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| F24 | Telegram /tunnel command creates tunnels (not just status) | **MISSING** — only shows info | `tunnel/index.ts:143-163` | Not tested | +| | All 4 providers (cloudflare, ngrok, bore, tailscale) | Correct | `providers/` | Not tested | +| | ViewerStore with TTL, auth, path validation | Correct | `viewer-store.ts` | Not tested | +| | TunnelRegistry (system/user, persistence, race handling) | Correct | `tunnel-registry.ts` | Not tested | +| | API endpoints (add, list, stop, stop-all) | Correct | `routes/tunnel.ts` | Not tested | + +--- + +## 1.10 Other Features + +| # | Requirement | Status | Location | Tests | +|---|-------------|--------|----------|-------| +| | File/Image/Audio support (bidirectional) | Correct | adapter.ts, file-service.ts, session.ts | Not tested | +| | Assistant UX (welcome, menu, prompt, action detect) | Correct | assistant.ts, menu.ts, action-detect.ts | Partial | +| | Agent catalog (registry, install, resolve) | Correct | agent-catalog.ts, agent-store.ts | Partial | +| | Generic handoff (integrate, capabilities) | Correct | agent-dependencies.ts, integrate.ts | Partial | + +--- + +# 2. Code-Level Bugs + +Issues in the code regardless of specs. + +| # | Severity | File | Issue | Fix | +|---|----------|------|-------|-----| +| C1 | **HIGH** | `session.ts:179` | processPrompt double-throw if session is "finished" | Guard: `if (this._status === "finished") return` | +| C2 | **HIGH** | `session-manager.ts:118` | cancelSession throws if error→cancelled transition | Add "cancelled" to valid transitions from "error" | +| C3 | **HIGH** | `config.ts:260-283` | save() writes invalid config to disk before validation | Validate before writing | +| C4 | **HIGH** | `log.ts:160-210` | Session logger pino.destination FD never closed | Add closeSessionLogger() in destroy() | +| C5 | **HIGH** | `activity-tracker.ts:74-76` | Thinking indicator stuck forever on maxThinkingDuration | Call removeThinkingIndicator() after stopRefresh | +| C6 | **HIGH** | `main.ts:119-272` | Spinner/logger not cleaned up on boot failure — user sees no error | Stop spinner + unmute logger in catch | +| C7 | MEDIUM | `session.ts:363-396` | Auto-name clearBuffer() discards crash error events | Replay error events before clearing | +| C8 | MEDIUM | `permission-gate.ts:33` | Timeout timer not unref'd — blocks shutdown 10min | Add .unref() | +| C9 | MEDIUM | `session-bridge.ts:40-53` | sendMessage middleware errors → unhandled rejections | Add .catch() or wrap in try-catch | +| C10 | MEDIUM | `draft-manager.ts:59-79` | Draft flush() race can create duplicate messages | Chain finalize flush onto flushPromise | +| C11 | MEDIUM | `streams.ts:3-26` | Node stream adapters missing close/cancel handlers | Add close/abort/cancel handlers | + +### Cross-Service Logic Issues (from deep review) + +These issues involve complex interactions between multiple services where timing, ordering, or error propagation can cause subtle bugs. + +| # | Severity | File | Issue | Fix | +|---|----------|------|-------|-----| +| C12 | **HIGH** | `core.ts:657` | **Lazy resume: threadId set AFTER createSession** — agent events emitted during spawn (before `session.threadId` is set) are silently dropped because adapter sees `threadId = ""` and skips the message. This could include error events from a failed spawn. | Set `session.threadId = message.threadId` BEFORE calling `createSession()`, or pass it as a constructor parameter | +| C13 | **HIGH** | `session-manager.ts:118-135` | **cancelSession: if abortPrompt throws (agent dead), session stays in map forever** — `cancel()` sends ACP request; if agent already crashed, connection is closed and `cancel()` throws. `markCancelled()` and `sessions.delete()` never execute. Session leaks in memory with no cleanup path. | Wrap `abortPrompt` in try-catch: `try { await session.abortPrompt() } catch {}` then proceed with markCancelled + delete | +| C14 | MEDIUM | `tool-card-state.ts:122-126` | **appendUsage immediate flush shows stale tool state** — `appendUsage()` calls `flush()` immediately, but pending tool updates may still be in the 500ms debounce window. The card renders with old tool status then the tool update arrives and re-renders. | Use `scheduleFlush()` instead of `flush()`, or flush pending debounce first | +| C15 | MEDIUM | `session-store.ts:136` | **Corrupt sessions.json silently lost** — on parse error, logs warning and starts empty. No `.bak` backup created. User loses all session records with no recovery path. | Rename corrupt file to `sessions.json.bak` before starting empty | +| C16 | MEDIUM | `draft-manager.ts:96-100` (shared) | **Shared DraftManager.finalize() doesn't remove draft from map** — after finalization, draft stays in map. `getOrCreate()` returns the stale finalized draft for subsequent prompts, potentially serving old buffer content. | Remove draft from map after finalization: `this.drafts.delete(sessionId)` | +| C17 | MEDIUM | `activity.ts:35-56` | **ThinkingIndicator: message sent but untrackable after dismiss** — if `dismiss()` called during SendQueue wait (3+ seconds), the message is still sent to Telegram but `msgId` is cleared. The thinking message persists in chat with no way to delete it. | After send completes, if `dismissed` is true, immediately delete the just-sent message | +| C18 | LOW | `session-bridge.ts:96-127` | **Middleware error fallback creates confusing control flow** — `.then().catch()` chain could theoretically double-process an event if inner try-catch doesn't catch everything. Currently safe because inner catch swallows all errors, but fragile for future changes. | Simplify to single try-catch with middleware as decorator | + +--- + +# 3. Architecture Review + +| # | Area | Issue | +|---|------|-------| +| A1 | **MessagingAdapter too thin** | Spec envisions rich base with send/edit/enqueueSend abstractions + composed primitives. Reality: thin dispatch layer. Each adapter replicates Telegram-specific logic. New adapters need ~1000+ lines, not the spec's 200-300. | +| A2 | **TelegramRenderer bypassed** | Renderer exists but adapter handlers directly call formatting functions. The renderer→adapter chain is not actually used for most message types. | +| A3 | **Usage tracking gap** | Core correctly emits usage:recorded events. Old consumer removed. New consumer (built-in-plugins/usage-plugin/) never created. Data flows to void. | +| A4 | **Config not simplified** | Plugin-specific schemas (channels, speech, tunnel, usage, api) and env vars remain in core ConfigSchema despite plugin extraction spec. | +| A5 | **Skill command UX** | Spec designed interactive button flow with callback routing. Implementation uses plain text. The interaction model is fundamentally different. | + +--- + +# 4. Test Coverage Gaps + +## Well Tested (no action needed) +- Session state machine (exhaustive transitions) +- PromptQueue (serial, abort, drain) +- PermissionGate (timeout, supersede, cleanup) +- SessionStore (CRUD, TTL, persistence, corruption) +- SessionManager (register, lookup, cancel, list) +- SessionFactory (spawn, resume, middleware, events) +- SessionBridge (comprehensive — wiring, permissions, lifecycle) +- MiddlewareChain (15 tests — timeout, errors, circuit breaking) +- SettingsManager + PluginRegistry (CRUD, persistence) +- LifecycleManager migration (version check, migrate call) +- AgentStore (atomic writes, CRUD, corruption) +- Context system (provider, manager, builder, cleaner, cache) +- SendQueue, DraftManager, ToolCallTracker, ToolCardState (shared primitives) +- suggestMatch (13 test cases) +- Speech service + Groq STT provider +- Action detection (detect + extended tests) + +## Missing Test Coverage + +| # | Area | What's untested | +|---|------|-----------------| +| T1 | **Lazy resume** | Entire flow — no tests exist | +| T2 | **adoptSession** | Only trivial mock test, no real flow test | +| T3 | **API route handlers** | All 15+ routes untested (only Router class tested) | +| T4 | **CLI commands** | All CLI commands untested | +| T5 | **Tunnel** | No tests for service, registry, providers, viewer store, server | +| T6 | **Telegram commands** | No tests for session/admin/menu/help handlers | +| T7 | **Telegram permissions** | Handler not tested | +| T8 | **TelegramRenderer** | No tests | +| T9 | **BaseRenderer + StreamAdapter** | No tests | +| T10 | **STT integration** | maybeTranscribeAudio() not tested | +| T11 | **TTS timeout** | 30s timeout not tested | +| T12 | **TTS toggle button** | Telegram callback not tested | +| T13 | **Plan in ToolCard** | Integration not tested | +| T14 | **ActivityTracker firstEvent** | Guard behavior not tested | +| T15 | **InstallContext + TerminalIO** | No tests | +| T16 | **File service** | No tests | +| T17 | **Agent catalog** | Only resolve/getAvailable — install, uninstall, refresh, availability untested | +| T18 | **Cleanup commands** | handleCleanup, handleCleanupEverything untested | +| T19 | **Archive flow** | Confirmation flow tested but wrong behavior verified | + +--- + +# 5. Fix Status + +## Completed (4 commits on fix/codebase-logic-review) + +| Commit | Items Fixed | +|--------|------------| +| `9038102` | C1, C2, C3, C4, C5, C6, C8, C9, C11, C12, C13, C14, C15, C16, F1, F9, F19, F20, F21 | +| `270ab52` | F11, F12, F13, C17, F22 | +| `18c590d` | F3, F4, F5, F6, F10 | +| `0bc34ca` | F18, F24 | + +**Total fixed: 30 items** (all code bugs + most feature issues) +**Tests: 134 files, 1746 tests passing** + +## Remaining (deferred) + +| # | Item | Reason | +|---|------|--------| +| F7 | Over-budget /resume interactive selection | Complex UI flow — TODO added | +| F14 | UsageMessage as separate deletable message | Design choice: merged into ToolCard | +| F15 | PlanCard separate message with 3.5s debounce | Design choice: merged into ToolCard | +| F16 | MessagingAdapter compose shared primitives | Architecture — separate effort | +| F17 | Skill commands as inline buttons | UX redesign — separate effort | +| F23 | Legacy config stripping after migration | Non-blocking — fallback works | +| A1-A5 | Architecture gaps | Separate design efforts | +| T1-T19 | Test coverage gaps | Ongoing | diff --git a/src/__tests__/api-server.test.ts b/src/__tests__/api-server.test.ts index 5a6f9f6..bf96bbc 100644 --- a/src/__tests__/api-server.test.ts +++ b/src/__tests__/api-server.test.ts @@ -33,6 +33,9 @@ describe("ApiServer", () => { agentManager: { getAvailableAgents: vi.fn(() => []), }, + agentCatalog: { + resolve: vi.fn((name: string) => ({ name, workingDirectory: "/tmp/ws" })), + }, configManager: { get: vi.fn(() => ({ defaultAgent: "claude", diff --git a/src/__tests__/archive-session.test.ts b/src/__tests__/archive-session.test.ts index 1ca496d..b549b7e 100644 --- a/src/__tests__/archive-session.test.ts +++ b/src/__tests__/archive-session.test.ts @@ -25,7 +25,24 @@ describe("handleArchive", () => { ); }); - it("shows confirmation for initializing session", async () => { + it("confirmation text describes topic recreation (not deletion)", async () => { + const ctx = mockCtx(456); + const core = { + sessionManager: { + getSessionByThread: vi.fn(() => ({ id: "sess-1", status: "active" })), + getRecordByThread: vi.fn(), + }, + } as any; + + await handleArchive(ctx, core); + const text = ctx.reply.mock.calls[0][0] as string; + expect(text).toContain("recreate it"); + expect(text).toContain("agent session will keep running"); + expect(text).not.toContain("Stop the agent"); + expect(text).not.toContain("Remove the session record"); + }); + + it("rejects initializing session", async () => { const ctx = mockCtx(456); const core = { sessionManager: { @@ -36,12 +53,12 @@ describe("handleArchive", () => { await handleArchive(ctx, core); expect(ctx.reply).toHaveBeenCalledWith( - expect.stringContaining("Archive this session"), - expect.objectContaining({ reply_markup: expect.any(Object) }), + expect.stringContaining("still initializing"), + expect.any(Object), ); }); - it("shows confirmation for orphan topic (no session, no record)", async () => { + it("rejects non-session topic (no session, no record)", async () => { const ctx = mockCtx(999); const core = { sessionManager: { @@ -52,8 +69,8 @@ describe("handleArchive", () => { await handleArchive(ctx, core); expect(ctx.reply).toHaveBeenCalledWith( - expect.stringContaining("Archive this session"), - expect.objectContaining({ reply_markup: expect.any(Object) }), + expect.stringContaining("not linked to a session"), + expect.any(Object), ); }); @@ -62,7 +79,7 @@ describe("handleArchive", () => { const core = { sessionManager: { getSessionByThread: vi.fn(() => undefined), - getRecordByThread: vi.fn(() => ({ sessionId: "stored-1" })), + getRecordByThread: vi.fn(() => ({ sessionId: "stored-1", status: "active" })), }, } as any; @@ -80,6 +97,24 @@ describe("handleArchive", () => { await handleArchive(ctx, core); expect(ctx.reply).not.toHaveBeenCalled(); }); + + it("allows archiving error/cancelled sessions", async () => { + for (const status of ["error", "cancelled"]) { + const ctx = mockCtx(456); + const core = { + sessionManager: { + getSessionByThread: vi.fn(() => ({ id: "sess-1", status })), + getRecordByThread: vi.fn(), + }, + } as any; + + await handleArchive(ctx, core); + expect(ctx.reply).toHaveBeenCalledWith( + expect.stringContaining("Archive this session"), + expect.objectContaining({ reply_markup: expect.any(Object) }), + ); + } + }); }); describe("handleArchiveConfirm", () => { @@ -97,10 +132,11 @@ describe("handleArchiveConfirm", () => { ); }); - it("calls core.archiveSession on confirm and notifies", async () => { + it("calls core.archiveSession and sends confirmation in new topic", async () => { + const sendMessage = vi.fn(() => Promise.resolve()); const core = { - archiveSession: vi.fn(() => Promise.resolve({ ok: true })), - notificationManager: { notifyAll: vi.fn(() => Promise.resolve()) }, + archiveSession: vi.fn(() => Promise.resolve({ ok: true, newThreadId: "789" })), + adapters: new Map([["telegram", { sendMessage }]]), } as any; const ctx = { callbackQuery: { data: "ar:yes:sess-1" }, @@ -110,10 +146,11 @@ describe("handleArchiveConfirm", () => { await handleArchiveConfirm(ctx, core, 123); expect(core.archiveSession).toHaveBeenCalledWith("sess-1"); - expect(core.notificationManager.notifyAll).toHaveBeenCalledWith( + expect(sendMessage).toHaveBeenCalledWith( + "sess-1", expect.objectContaining({ - sessionId: "sess-1", - type: "completed", + type: "text", + text: expect.stringContaining("Chat history cleared"), }), ); }); @@ -121,6 +158,7 @@ describe("handleArchiveConfirm", () => { it("shows error when archive fails", async () => { const core = { archiveSession: vi.fn(() => Promise.resolve({ ok: false, error: "No permission" })), + notificationManager: { notifyAll: vi.fn(() => Promise.resolve()) }, } as any; const ctx = { callbackQuery: { data: "ar:yes:sess-1" }, @@ -135,46 +173,23 @@ describe("handleArchiveConfirm", () => { ); }); - it("handles orphan topic deletion", async () => { + it("does not kill agent or remove session record", async () => { + const sendMessage = vi.fn(() => Promise.resolve()); + const cancelSession = vi.fn(); + const removeRecord = vi.fn(); const core = { - notificationManager: { notifyAll: vi.fn(() => Promise.resolve()) }, + archiveSession: vi.fn(() => Promise.resolve({ ok: true, newThreadId: "789" })), + adapters: new Map([["telegram", { sendMessage }]]), + sessionManager: { cancelSession, removeRecord }, } as any; const ctx = { - callbackQuery: { data: "ar:yes:topic:999" }, + callbackQuery: { data: "ar:yes:sess-1" }, answerCallbackQuery: vi.fn(() => Promise.resolve()), editMessageText: vi.fn(() => Promise.resolve()), - api: { deleteForumTopic: vi.fn(() => Promise.resolve()) }, } as any; await handleArchiveConfirm(ctx, core, 123); - expect(ctx.api.deleteForumTopic).toHaveBeenCalledWith(123, 999); - expect(core.notificationManager.notifyAll).toHaveBeenCalledWith( - expect.objectContaining({ - sessionId: "system", - sessionName: "Orphan topic #999", - type: "completed", - }), - ); - }); - - it("notifies on orphan topic delete failure", async () => { - const core = { - notificationManager: { notifyAll: vi.fn(() => Promise.resolve()) }, - } as any; - const ctx = { - callbackQuery: { data: "ar:yes:topic:999" }, - answerCallbackQuery: vi.fn(() => Promise.resolve()), - editMessageText: vi.fn(() => Promise.resolve()), - api: { deleteForumTopic: vi.fn(() => Promise.reject(new Error("forbidden"))) }, - } as any; - - await handleArchiveConfirm(ctx, core, 123); - expect(core.notificationManager.notifyAll).toHaveBeenCalledWith( - expect.objectContaining({ - sessionId: "system", - type: "error", - summary: expect.stringContaining("forbidden"), - }), - ); + expect(cancelSession).not.toHaveBeenCalled(); + expect(removeRecord).not.toHaveBeenCalled(); }); }); diff --git a/src/cli/commands/api.ts b/src/cli/commands/api.ts index cb17096..054eac2 100644 --- a/src/cli/commands/api.ts +++ b/src/cli/commands/api.ts @@ -412,18 +412,19 @@ Shows the version of the currently running daemon process. console.error(`Error: ${data.error}`) process.exit(1) } + const s = (data.session ?? data) as Record console.log(`Session details:`) - console.log(` ID : ${data.id}`) - console.log(` Agent : ${data.agent}`) - console.log(` Status : ${data.status}`) - console.log(` Name : ${data.name ?? '(none)'}`) - console.log(` Workspace : ${data.workspace}`) - console.log(` Created : ${data.createdAt}`) - console.log(` Dangerous : ${data.dangerous}`) - console.log(` Queue depth : ${data.queueDepth}`) - console.log(` Prompt active : ${data.promptActive}`) - console.log(` Channel : ${data.channelId ?? '(none)'}`) - console.log(` Thread : ${data.threadId ?? '(none)'}`) + console.log(` ID : ${s.id}`) + console.log(` Agent : ${s.agent}`) + console.log(` Status : ${s.status}`) + console.log(` Name : ${s.name ?? '(none)'}`) + console.log(` Workspace : ${s.workspace}`) + console.log(` Created : ${s.createdAt}`) + console.log(` Dangerous : ${s.dangerousMode}`) + console.log(` Queue depth : ${s.queueDepth}`) + console.log(` Prompt active : ${s.promptRunning}`) + console.log(` Channel : ${s.channelId ?? '(none)'}`) + console.log(` Thread : ${s.threadId ?? '(none)'}`) } else if (subCmd === 'dangerous') { const sessionId = args[2] @@ -456,19 +457,23 @@ Shows the version of the currently running daemon process. console.error(`Error: ${data.error}`) process.exit(1) } - const uptimeSeconds = typeof data.uptimeSeconds === 'number' ? data.uptimeSeconds : 0 + const uptimeMs = typeof data.uptime === 'number' ? data.uptime : 0 + const uptimeSeconds = Math.floor(uptimeMs / 1000) const hours = Math.floor(uptimeSeconds / 3600) const minutes = Math.floor((uptimeSeconds % 3600) / 60) - const memoryBytes = typeof data.memoryUsage === 'number' ? data.memoryUsage : 0 - const memoryMB = (memoryBytes / 1024 / 1024).toFixed(1) + const mem = data.memory as Record | undefined + const memoryMB = mem ? (mem.rss / 1024 / 1024).toFixed(1) : '0.0' const sessions = data.sessions as Record ?? {} + const tunnel = data.tunnel as Record | undefined + const tunnelStr = tunnel?.enabled ? `${tunnel.url}` : 'disabled' + const adapters = Array.isArray(data.adapters) ? data.adapters.join(', ') : String(data.adapters ?? 'none') console.log(`Status : ${data.status}`) console.log(`Uptime : ${hours}h ${minutes}m`) console.log(`Version : ${data.version}`) console.log(`Memory : ${memoryMB} MB`) console.log(`Sessions : ${sessions.active ?? 0} active / ${sessions.total ?? 0} total`) - console.log(`Adapters : ${data.adapters}`) - console.log(`Tunnel : ${data.tunnel}`) + console.log(`Adapters : ${adapters}`) + console.log(`Tunnel : ${tunnelStr}`) } else if (subCmd === 'restart') { const res = await apiCall(port, '/api/restart', { method: 'POST' }) diff --git a/src/core/adapter-primitives/__tests__/activity-tracker.test.ts b/src/core/adapter-primitives/__tests__/activity-tracker.test.ts new file mode 100644 index 0000000..60ff5cb --- /dev/null +++ b/src/core/adapter-primitives/__tests__/activity-tracker.test.ts @@ -0,0 +1,32 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { ActivityTracker, type ActivityCallbacks } from "../primitives/activity-tracker.js"; + +function mockCallbacks(): ActivityCallbacks { + return { + sendThinkingIndicator: vi.fn().mockResolvedValue(undefined), + updateThinkingIndicator: vi.fn().mockResolvedValue(undefined), + removeThinkingIndicator: vi.fn().mockResolvedValue(undefined), + }; +} + +describe("ActivityTracker", () => { + let tracker: ActivityTracker; + + afterEach(() => { + tracker?.destroy(); + }); + + it("calls removeThinkingIndicator when maxThinkingDuration is exceeded", async () => { + tracker = new ActivityTracker({ + thinkingRefreshInterval: 50, + maxThinkingDuration: 100, + }); + + const callbacks = mockCallbacks(); + tracker.onThinkingStart("sess-1", callbacks); + + await new Promise((r) => setTimeout(r, 200)); + + expect(callbacks.removeThinkingIndicator).toHaveBeenCalled(); + }); +}); diff --git a/src/core/adapter-primitives/__tests__/draft-manager.test.ts b/src/core/adapter-primitives/__tests__/draft-manager.test.ts new file mode 100644 index 0000000..193600b --- /dev/null +++ b/src/core/adapter-primitives/__tests__/draft-manager.test.ts @@ -0,0 +1,23 @@ +import { describe, it, expect, vi } from "vitest"; +import { DraftManager } from "../primitives/draft-manager.js"; + +describe("DraftManager", () => { + it("returns a new empty draft after finalize removes the old one", async () => { + const onFlush = vi.fn().mockResolvedValue("msg-1"); + const manager = new DraftManager({ + flushInterval: 10, + maxLength: 10000, + onFlush, + }); + + const draft1 = manager.getOrCreate("sess-1"); + draft1.append("hello"); + await manager.finalize("sess-1"); + + const draft2 = manager.getOrCreate("sess-1"); + expect(draft2).not.toBe(draft1); + expect(draft2.isEmpty).toBe(true); + + manager.destroyAll(); + }); +}); diff --git a/src/core/adapter-primitives/primitives/__tests__/tool-card-state.test.ts b/src/core/adapter-primitives/primitives/__tests__/tool-card-state.test.ts index e7ec866..8ffe166 100644 --- a/src/core/adapter-primitives/primitives/__tests__/tool-card-state.test.ts +++ b/src/core/adapter-primitives/primitives/__tests__/tool-card-state.test.ts @@ -96,12 +96,13 @@ describe("ToolCardState", () => { card.destroy(); }); - it("appendUsage sets usage and force flushes", () => { + it("appendUsage sets usage and schedules flush", () => { const onFlush = vi.fn(); const card = new ToolCardState({ onFlush, verbosity: "medium" }); card.addTool(makeTool("t1", "Read"), "read", { file_path: "src/a.ts" }); onFlush.mockClear(); card.appendUsage({ tokensUsed: 5000, cost: 0.05 }); + vi.advanceTimersByTime(500); expect(onFlush).toHaveBeenCalledTimes(1); const state = onFlush.mock.lastCall![0]; expect(state.usage).toEqual({ tokensUsed: 5000, cost: 0.05 }); diff --git a/src/core/adapter-primitives/primitives/activity-tracker.ts b/src/core/adapter-primitives/primitives/activity-tracker.ts index 363e7d6..020633d 100644 --- a/src/core/adapter-primitives/primitives/activity-tracker.ts +++ b/src/core/adapter-primitives/primitives/activity-tracker.ts @@ -72,7 +72,9 @@ export class ActivityTracker { return } if (Date.now() - state.startTime >= this.config.maxThinkingDuration) { + state.dismissed = true this.stopRefresh(state) + state.callbacks.removeThinkingIndicator().catch(() => {}) return } state.callbacks.updateThinkingIndicator().catch(() => {}) diff --git a/src/core/adapter-primitives/primitives/draft-manager.ts b/src/core/adapter-primitives/primitives/draft-manager.ts index 9eaba56..5c4a55a 100644 --- a/src/core/adapter-primitives/primitives/draft-manager.ts +++ b/src/core/adapter-primitives/primitives/draft-manager.ts @@ -97,6 +97,7 @@ export class DraftManager { const draft = this.drafts.get(sessionId) if (!draft) return await draft.finalize() + this.drafts.delete(sessionId) } async finalizeAll(): Promise { diff --git a/src/core/adapter-primitives/primitives/tool-card-state.ts b/src/core/adapter-primitives/primitives/tool-card-state.ts index 9ead2a1..bbf9a84 100644 --- a/src/core/adapter-primitives/primitives/tool-card-state.ts +++ b/src/core/adapter-primitives/primitives/tool-card-state.ts @@ -122,7 +122,7 @@ export class ToolCardState { appendUsage(usage: UsageData): void { if (this.finalized) return; this.usage = usage; - this.flush(); + this.scheduleFlush(); } finalize(): void { diff --git a/src/core/channel.ts b/src/core/channel.ts index 283d062..65c36cc 100644 --- a/src/core/channel.ts +++ b/src/core/channel.ts @@ -30,7 +30,10 @@ export interface IChannelAdapter { createSessionThread(sessionId: string, name: string): Promise // returns threadId renameSessionThread(sessionId: string, newName: string): Promise deleteSessionThread?(sessionId: string): Promise - archiveSessionTopic?(sessionId: string): Promise + archiveSessionTopic?(sessionId: string): Promise + + // TTS strip — optional, called after TTS audio is synthesized to remove [TTS] block from text + stripTTSBlock?(sessionId: string): Promise // Skill commands — optional sendSkillCommands?(sessionId: string, commands: AgentCommand[]): Promise @@ -64,5 +67,5 @@ export abstract class ChannelAdapter implements IChannelAdapter async sendSkillCommands(_sessionId: string, _commands: AgentCommand[]): Promise {} async cleanupSkillCommands(_sessionId: string): Promise {} - async archiveSessionTopic(_sessionId: string): Promise {} + async archiveSessionTopic(_sessionId: string): Promise { return ""; } } diff --git a/src/core/config/config.ts b/src/core/config/config.ts index c0acd84..759b2d3 100644 --- a/src/core/config/config.ts +++ b/src/core/config/config.ts @@ -262,15 +262,17 @@ export class ConfigManager extends EventEmitter { changePath?: string, ): Promise { const oldConfig = this.config ? structuredClone(this.config) : undefined; - // Read current file, merge updates, write back + // Read current file, merge updates const raw = JSON.parse(fs.readFileSync(this.configPath, "utf-8")); this.deepMerge(raw, updates); - fs.writeFileSync(this.configPath, JSON.stringify(raw, null, 2)); - // Re-validate and update in-memory config + // Validate BEFORE writing to disk const result = ConfigSchema.safeParse(raw); - if (result.success) { - this.config = result.data; + if (!result.success) { + log.error({ errors: result.error.issues }, "Config validation failed, not saving"); + return; } + fs.writeFileSync(this.configPath, JSON.stringify(raw, null, 2)); + this.config = result.data; // Emit change event if path provided if (changePath) { const { getConfigValue } = await import("./config-registry.js"); diff --git a/src/core/core.ts b/src/core/core.ts index cab9eed..d1e2e90 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -186,47 +186,43 @@ export class OpenACPCore { // --- Archive --- - async archiveSession(sessionId: string): Promise<{ ok: true } | { ok: false; error: string }> { + async archiveSession(sessionId: string): Promise<{ ok: true; newThreadId: string } | { ok: false; error: string }> { const session = this.sessionManager.getSession(sessionId); - const record = this.sessionManager.getSessionRecord(sessionId); + if (!session) return { ok: false, error: "Session not found (must be in memory)" }; - if (!session && !record) return { ok: false, error: "Session not found" }; + // Must be active (not initializing or finished) + if (session.status !== "active" && session.status !== "cancelled" && session.status !== "error") { + return { ok: false, error: `Cannot archive session in '${session.status}' state` }; + } - const channelId = session?.channelId ?? record?.channelId; - if (!channelId) return { ok: false, error: "No channel for session" }; - - const adapter = this.adapters.get(channelId); + const adapter = this.adapters.get(session.channelId); if (!adapter) return { ok: false, error: "Adapter not found for session" }; + if (!adapter.archiveSessionTopic) return { ok: false, error: "Adapter does not support topic archiving" }; try { - // 1. Delete topic — if session is in memory use archiveSessionTopic (cleans up trackers), - // otherwise use deleteSessionThread (looks up topicId from record) - if (session) { - await adapter.archiveSessionTopic?.(session.id); - } else { - await adapter.deleteSessionThread?.(sessionId); - } + // archiveSessionTopic handles: cleanup trackers → delete old topic → create new topic + const newThreadId = await adapter.archiveSessionTopic(session.id); - // 2. Cancel the session if in memory (stop agent) - if (session) { - try { - await this.sessionManager.cancelSession(sessionId); - } catch { - // Session may already be finished/cancelled - } finally { - // Clear archiving flag after cancel completes — prevents race window - // where agent events try to send to deleted topic - session.archiving = false; + // Rewire session to new topic + session.threadId = newThreadId; + + // Update session store with new topic ID (best-effort — topic is already recreated) + try { + const platform: Record = {}; + if (session.channelId === "telegram") { + platform.topicId = Number(newThreadId); + } else { + platform.threadId = newThreadId; } + await this.sessionManager.patchRecord(sessionId, { platform }); + } catch (patchErr) { + log.warn({ err: patchErr, sessionId }, "Failed to update session record after archive — session will work but may not survive restart"); } - // 3. Remove session record - await this.sessionManager.removeRecord(sessionId); - - return { ok: true }; + return { ok: true, newThreadId }; } catch (err) { - // Clear archiving flag on error too - if (session) session.archiving = false; + // Clear archiving flag on error + session.archiving = false; return { ok: false, error: (err as Error).message }; } } @@ -308,10 +304,16 @@ export class OpenACPCore { existingSessionId?: string; createThread?: boolean; initialName?: string; + threadId?: string; }): Promise { // 1-3. Spawn/resume agent, create Session, register in SessionManager const session = await this.sessionFactory.create(params); + // Set threadId early so agent events during bridge.connect() can find the thread + if (params.threadId) { + session.threadId = params.threadId; + } + // 4. Create thread if needed const adapter = this.adapters.get(params.channelId); if (params.createThread && adapter) { @@ -622,8 +624,8 @@ export class OpenACPCore { return null; } - // Don't resume errored sessions (cancelled sessions can still be resumed) - if (record.status === "error") { + // Don't resume errored or cancelled sessions + if (record.status === "error" || record.status === "cancelled") { log.debug( { threadId: message.threadId, @@ -653,8 +655,8 @@ export class OpenACPCore { resumeAgentSessionId: record.agentSessionId, existingSessionId: record.sessionId, initialName: record.name, + threadId: message.threadId, }); - session.threadId = message.threadId; session.activate(); session.dangerousMode = record.dangerousMode ?? false; diff --git a/src/core/plugin/__tests__/lifecycle-migration.test.ts b/src/core/plugin/__tests__/lifecycle-migration.test.ts index 8629e24..c9c79dc 100644 --- a/src/core/plugin/__tests__/lifecycle-migration.test.ts +++ b/src/core/plugin/__tests__/lifecycle-migration.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from 'vitest' +import { z } from 'zod' import { LifecycleManager } from '../lifecycle-manager.js' import type { OpenACPPlugin, MigrateContext } from '../types.js' import type { SettingsManager } from '../settings-manager.js' @@ -197,3 +198,152 @@ describe('LifecycleManager — Migration Support', () => { expect(emitEvents.some(e => e.event === 'plugin:disabled')).toBe(true) }) }) + +describe('LifecycleManager — Settings Validation', () => { + it('skips plugin when settingsSchema validation fails (setup not called)', async () => { + const schema = z.object({ + apiKey: z.string().min(1), + port: z.number().int().positive(), + }) + + const plugin = makePlugin('validated-plugin', { + settingsSchema: schema, + }) + + // Invalid settings: missing apiKey, port is a string + const settingsMgr = mockSettingsManager({ 'validated-plugin': { port: 'not-a-number' } }) + // Make validateSettings actually validate against the schema + ;(settingsMgr.validateSettings as ReturnType).mockImplementation( + (_name: string, settings: unknown, s?: z.ZodSchema) => { + if (!s) return { valid: true } + const result = s.safeParse(settings) + if (result.success) return { valid: true } + return { + valid: false, + errors: result.error.errors.map( + (e: { path: (string | number)[]; message: string }) => `${e.path.join('.')}: ${e.message}`, + ), + } + }, + ) + + const emitEvents: Array<{ event: string; payload: unknown }> = [] + + const mgr = new LifecycleManager({ + settingsManager: settingsMgr, + eventBus: { + on() {}, + off() {}, + emit(event: string, payload: unknown) { emitEvents.push({ event, payload }) }, + }, + }) + await mgr.boot([plugin]) + + expect(plugin.setup).not.toHaveBeenCalled() + expect(mgr.loadedPlugins).not.toContain('validated-plugin') + expect(mgr.failedPlugins).toContain('validated-plugin') + expect(emitEvents.some(e => e.event === 'plugin:failed')).toBe(true) + }) + + it('proceeds with setup when settingsSchema validation passes', async () => { + const schema = z.object({ + apiKey: z.string().min(1), + port: z.number().int().positive(), + }) + + const plugin = makePlugin('validated-plugin', { + settingsSchema: schema, + }) + + const settingsMgr = mockSettingsManager({ 'validated-plugin': { apiKey: 'abc123', port: 8080 } }) + ;(settingsMgr.validateSettings as ReturnType).mockImplementation( + (_name: string, settings: unknown, s?: z.ZodSchema) => { + if (!s) return { valid: true } + const result = s.safeParse(settings) + if (result.success) return { valid: true } + return { + valid: false, + errors: result.error.errors.map( + (e: { path: (string | number)[]; message: string }) => `${e.path.join('.')}: ${e.message}`, + ), + } + }, + ) + + const mgr = new LifecycleManager({ + settingsManager: settingsMgr, + }) + await mgr.boot([plugin]) + + expect(plugin.setup).toHaveBeenCalled() + expect(mgr.loadedPlugins).toContain('validated-plugin') + }) + + it('skips validation when plugin has no settingsSchema', async () => { + const plugin = makePlugin('no-schema-plugin') + + const settingsMgr = mockSettingsManager({ 'no-schema-plugin': { anything: 'goes' } }) + + const mgr = new LifecycleManager({ + settingsManager: settingsMgr, + }) + await mgr.boot([plugin]) + + expect(settingsMgr.validateSettings).not.toHaveBeenCalled() + expect(plugin.setup).toHaveBeenCalled() + expect(mgr.loadedPlugins).toContain('no-schema-plugin') + }) + + it('skips validation when no settingsManager is available', async () => { + const schema = z.object({ key: z.string() }) + const plugin = makePlugin('no-mgr-plugin', { settingsSchema: schema }) + + const mgr = new LifecycleManager({}) + await mgr.boot([plugin]) + + expect(plugin.setup).toHaveBeenCalled() + expect(mgr.loadedPlugins).toContain('no-mgr-plugin') + }) + + it('validates settings after migration completes', async () => { + const schema = z.object({ + apiKey: z.string().min(1), + }) + + const migrateFn = vi.fn(async (_ctx: MigrateContext, _old: unknown, _oldVer: string) => ({ + apiKey: '', // Returns invalid settings after migration + })) + + const plugin = makePlugin('migrate-validate-plugin', { + version: '2.0.0', + migrate: migrateFn, + settingsSchema: schema, + }) + + const registry = mockPluginRegistry({ 'migrate-validate-plugin': { version: '1.0.0' } }) + const settingsMgr = mockSettingsManager({ 'migrate-validate-plugin': { apiKey: '' } }) + ;(settingsMgr.validateSettings as ReturnType).mockImplementation( + (_name: string, settings: unknown, s?: z.ZodSchema) => { + if (!s) return { valid: true } + const result = s.safeParse(settings) + if (result.success) return { valid: true } + return { + valid: false, + errors: result.error.errors.map( + (e: { path: (string | number)[]; message: string }) => `${e.path.join('.')}: ${e.message}`, + ), + } + }, + ) + + const mgr = new LifecycleManager({ + pluginRegistry: registry, + settingsManager: settingsMgr, + }) + await mgr.boot([plugin]) + + expect(migrateFn).toHaveBeenCalled() + expect(plugin.setup).not.toHaveBeenCalled() + expect(mgr.failedPlugins).toContain('migrate-validate-plugin') + }) +}) diff --git a/src/core/plugin/lifecycle-manager.ts b/src/core/plugin/lifecycle-manager.ts index d6cb1c3..58c0adc 100644 --- a/src/core/plugin/lifecycle-manager.ts +++ b/src/core/plugin/lifecycle-manager.ts @@ -223,6 +223,17 @@ export class LifecycleManager { this.getPluginLogger(plugin.name).debug('No settingsManager, using legacy config') } + // Validate settings against schema if plugin provides one + if (plugin.settingsSchema && this.settingsManager) { + const validation = this.settingsManager.validateSettings(plugin.name, pluginConfig, plugin.settingsSchema) + if (!validation.valid) { + this._failed.add(plugin.name) + this.getPluginLogger(plugin.name).error(`Settings validation failed: ${validation.errors?.join('; ')}`) + this.eventBus?.emit('plugin:failed', { name: plugin.name, error: `Settings validation failed: ${validation.errors?.join('; ')}` }) + continue + } + } + // Create context for this plugin const ctx = createPluginContext({ pluginName: plugin.name, diff --git a/src/core/sessions/__tests__/session-comprehensive.test.ts b/src/core/sessions/__tests__/session-comprehensive.test.ts index 5af8d3b..c7bd24c 100644 --- a/src/core/sessions/__tests__/session-comprehensive.test.ts +++ b/src/core/sessions/__tests__/session-comprehensive.test.ts @@ -32,7 +32,7 @@ describe("Session — State Machine Exhaustive Transitions", () => { // Valid transitions according to source: // initializing -> active, error // active -> error, finished, cancelled - // error -> active + // error -> active, cancelled // cancelled -> active // finished -> (nothing) @@ -129,10 +129,11 @@ describe("Session — State Machine Exhaustive Transitions", () => { expect(() => session.finish()).toThrow("Invalid session transition: error → finished"); }); - it("error → cancelled throws", () => { + it("error → cancelled is valid", () => { const session = createTestSession(); session.fail("oops"); - expect(() => session.markCancelled()).toThrow("Invalid session transition: error → cancelled"); + expect(() => session.markCancelled()).not.toThrow(); + expect(session.status).toBe("cancelled"); }); it("cancelled → finished throws", () => { diff --git a/src/core/sessions/__tests__/session-lifecycle.test.ts b/src/core/sessions/__tests__/session-lifecycle.test.ts index 1bb8036..f71afa4 100644 --- a/src/core/sessions/__tests__/session-lifecycle.test.ts +++ b/src/core/sessions/__tests__/session-lifecycle.test.ts @@ -392,4 +392,15 @@ describe("Session - Context Injection", () => { await vi.waitFor(() => expect(agent.prompt).toHaveBeenCalledTimes(1)); expect(agent.prompt.mock.calls[0][0]).toBe("hello"); }); + + it("processPrompt silently returns if session is finished", async () => { + const agent = mockAgentInstance(); + const session = createTestSession(agent); + session.activate(); + session.finish("done"); + const callsBefore = agent.prompt.mock.calls.length; + await session.enqueuePrompt("hello after finish"); + await new Promise((r) => setTimeout(r, 50)); + expect(agent.prompt.mock.calls.length).toBe(callsBefore); + }); }); diff --git a/src/core/sessions/__tests__/session-manager.test.ts b/src/core/sessions/__tests__/session-manager.test.ts index e1cac79..e70e8ee 100644 --- a/src/core/sessions/__tests__/session-manager.test.ts +++ b/src/core/sessions/__tests__/session-manager.test.ts @@ -249,6 +249,18 @@ describe('SessionManager', () => { expect(manager.getSession('sess-cancel-mem')).toBeUndefined() }) + it('completes cleanup even if abortPrompt throws', async () => { + const session = createSession({ id: 'sess-dead-agent' }) + session.activate() + session.agentInstance.cancel = vi.fn().mockRejectedValue(new Error('agent dead')) + manager.registerSession(session) + + await manager.cancelSession('sess-dead-agent') + + expect(session.status).toBe('cancelled') + expect(manager.getSession('sess-dead-agent')).toBeUndefined() + }) + it('does not re-save if already cancelled', async () => { await store.save({ sessionId: 'already-cancelled', diff --git a/src/core/sessions/__tests__/session-state-machine.test.ts b/src/core/sessions/__tests__/session-state-machine.test.ts index ef52222..b1133a8 100644 --- a/src/core/sessions/__tests__/session-state-machine.test.ts +++ b/src/core/sessions/__tests__/session-state-machine.test.ts @@ -85,6 +85,14 @@ describe("Session state machine", () => { session.activate(); expect(session.status).toBe("active"); }); + + it("error → cancelled via markCancelled()", () => { + const session = createSession(); + session.activate(); + session.fail("something broke"); + expect(() => session.markCancelled()).not.toThrow(); + expect(session.status).toBe("cancelled"); + }); }); describe("invalid transitions", () => { @@ -124,12 +132,6 @@ describe("Session state machine", () => { session.fail("err"); expect(() => session.finish("done")).toThrow(); }); - - it("error → cancelled throws", () => { - const session = createSession(); - session.fail("err"); - expect(() => session.markCancelled()).toThrow(); - }); }); describe("status_change event", () => { diff --git a/src/core/sessions/__tests__/session-tts.test.ts b/src/core/sessions/__tests__/session-tts.test.ts index bbfdad8..945877e 100644 --- a/src/core/sessions/__tests__/session-tts.test.ts +++ b/src/core/sessions/__tests__/session-tts.test.ts @@ -110,6 +110,25 @@ describe("Session TTS integration", () => { expect(session.voiceMode).toBe("off"); }); + it("preserves voiceMode 'next' when prompt fails", async () => { + const agent = mockAgent(); + const speech = mockSpeechService(true); + const session = createSession(agent, speech); + session.setVoiceMode("next"); + + (agent.prompt as any).mockRejectedValue(new Error("agent crashed")); + + await session.enqueuePrompt("hello"); + + await vi.waitFor(() => { + expect(agent.prompt).toHaveBeenCalled(); + }); + + // Allow queue error handler to run + await new Promise((r) => setTimeout(r, 50)); + expect(session.voiceMode).toBe("next"); + }); + it("keeps voiceMode 'on' after prompt", async () => { const agent = mockAgent(); const speech = mockSpeechService(true); diff --git a/src/core/sessions/permission-gate.ts b/src/core/sessions/permission-gate.ts index 1e86904..86e21a0 100644 --- a/src/core/sessions/permission-gate.ts +++ b/src/core/sessions/permission-gate.ts @@ -33,6 +33,9 @@ export class PermissionGate { this.timeoutTimer = setTimeout(() => { this.reject("Permission request timed out (no response received)"); }, this.timeoutMs); + if (typeof this.timeoutTimer === 'object' && 'unref' in this.timeoutTimer) { + (this.timeoutTimer as NodeJS.Timeout).unref(); + } }); } diff --git a/src/core/sessions/session-bridge.ts b/src/core/sessions/session-bridge.ts index 1379e81..826b523 100644 --- a/src/core/sessions/session-bridge.ts +++ b/src/core/sessions/session-bridge.ts @@ -38,17 +38,21 @@ export class SessionBridge { /** Send message to adapter, optionally running through message:outgoing middleware */ private async sendMessage(sessionId: string, message: ReturnType): Promise { - const mw = this.deps.middlewareChain; - if (mw) { - const result = await mw.execute('message:outgoing', { sessionId, message }, async (m) => m); - if (!result) return; // blocked by middleware - this.adapter.sendMessage(sessionId, result.message).catch((err) => { - log.error({ err, sessionId }, "Failed to send message to adapter"); - }); - } else { - this.adapter.sendMessage(sessionId, message).catch((err) => { - log.error({ err, sessionId }, "Failed to send message to adapter"); - }); + try { + const mw = this.deps.middlewareChain; + if (mw) { + const result = await mw.execute('message:outgoing', { sessionId, message }, async (m) => m); + if (!result) return; + this.adapter.sendMessage(sessionId, result.message).catch((err) => { + log.error({ err, sessionId }, "Failed to send message to adapter"); + }); + } else { + this.adapter.sendMessage(sessionId, message).catch((err) => { + log.error({ err, sessionId }, "Failed to send message to adapter"); + }); + } + } catch (err) { + log.error({ err, sessionId }, "Error in sendMessage middleware"); } } @@ -264,6 +268,10 @@ export class SessionBridge { outgoing = this.deps.messageTransformer.transform(event); this.sendMessage(this.session.id, outgoing); break; + + case "tts_strip": + this.adapter.stripTTSBlock?.(this.session.id); + break; } this.deps.eventBus?.emit("agent:event", { diff --git a/src/core/sessions/session-manager.ts b/src/core/sessions/session-manager.ts index 45bd7c7..54bfdb6 100644 --- a/src/core/sessions/session-manager.ts +++ b/src/core/sessions/session-manager.ts @@ -118,7 +118,11 @@ export class SessionManager { async cancelSession(sessionId: string): Promise { const session = this.sessions.get(sessionId); if (session) { - await session.abortPrompt(); + try { + await session.abortPrompt(); + } catch { + // Agent may already be dead — continue with cleanup + } session.markCancelled(); this.sessions.delete(sessionId); } diff --git a/src/core/sessions/session-store.ts b/src/core/sessions/session-store.ts index 7a99c70..a879319 100644 --- a/src/core/sessions/session-store.ts +++ b/src/core/sessions/session-store.ts @@ -134,7 +134,10 @@ export class JsonFileSessionStore implements SessionStore { } log.debug({ count: this.records.size }, "Loaded session records"); } catch (err) { - log.error({ err }, "Failed to load session store"); + log.error({ err }, "Failed to load session store, backing up corrupt file"); + try { + fs.renameSync(this.filePath, `${this.filePath}.bak`); + } catch { /* best effort */ } } } diff --git a/src/core/sessions/session.ts b/src/core/sessions/session.ts index 2ff389e..2fdf62b 100644 --- a/src/core/sessions/session.ts +++ b/src/core/sessions/session.ts @@ -4,7 +4,7 @@ import type { AgentCapabilities, AgentEvent, Attachment, PermissionRequest, Sess import { TypedEmitter } from "../utils/typed-emitter.js"; import { PromptQueue } from "./prompt-queue.js"; import { PermissionGate } from "./permission-gate.js"; -import { createChildLogger, createSessionLogger, type Logger } from "../utils/log.js"; +import { createChildLogger, createSessionLogger, closeSessionLogger, type Logger } from "../utils/log.js"; import type { SpeechService } from "../../plugins/speech/exports.js"; import type { MiddlewareChain } from "../plugin/middleware-chain.js"; import * as fs from "node:fs"; @@ -20,7 +20,7 @@ export const TTS_TIMEOUT_MS = 30_000; const VALID_TRANSITIONS: Record> = { initializing: new Set(["active", "error"]), active: new Set(["error", "finished", "cancelled"]), - error: new Set(["active"]), + error: new Set(["active", "cancelled"]), cancelled: new Set(["active"]), finished: new Set(), }; @@ -174,6 +174,9 @@ export class Session extends TypedEmitter { return; } + // Don't process prompts for finished sessions (queue may still drain) + if (this._status === "finished") return; + this.promptCount++; if (this._status === "initializing" || this._status === "cancelled" || this._status === "error") { @@ -200,9 +203,6 @@ export class Session extends TypedEmitter { // TTS: inject prompt instruction if (ttsActive) { processed.text += TTS_PROMPT_INSTRUCTION; - if (this.voiceMode === "next") { - this.voiceMode = "off"; - } } // TTS: set up text accumulator before prompting @@ -234,6 +234,10 @@ export class Session extends TypedEmitter { if (contextUsed) { this.pendingContext = null; } + // Reset "next" voice mode only after successful prompt + if (ttsActive && this.voiceMode === "next") { + this.voiceMode = "off"; + } } finally { if (accumulatorListener) { this.off("agent_event", accumulatorListener); @@ -350,6 +354,7 @@ export class Session extends TypedEmitter { data: base64, mimeType: result.mimeType, }); + this.emit("agent_event", { type: "tts_strip" }); this.log.info("TTS synthesis completed"); } finally { clearTimeout(ttsTimer!); @@ -500,5 +505,6 @@ export class Session extends TypedEmitter { // Clear queued prompts this.queue.clear(); await this.agentInstance.destroy(); + closeSessionLogger(this.log); } } diff --git a/src/core/types.ts b/src/core/types.ts index 9de8aaf..6e35735 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -112,7 +112,8 @@ export type AgentEvent = | { type: "model_update"; modelId: string } | { type: "user_message_chunk"; content: string } | { type: "resource_content"; uri: string; name: string; text?: string; blob?: string; mimeType?: string } - | { type: "resource_link"; uri: string; name: string; mimeType?: string; title?: string; description?: string; size?: number }; + | { type: "resource_link"; uri: string; name: string; mimeType?: string; title?: string; description?: string; size?: number } + | { type: "tts_strip" }; export interface PlanEntry { content: string; diff --git a/src/core/utils/log.ts b/src/core/utils/log.ts index 33690d4..92229d6 100644 --- a/src/core/utils/log.ts +++ b/src/core/utils/log.ts @@ -209,6 +209,13 @@ export function createSessionLogger(sessionId: string, parentLogger: Logger): Lo } } +export function closeSessionLogger(logger: Logger): void { + const dest = (logger as any).__sessionDest + if (dest && typeof dest.destroy === 'function') { + dest.destroy() + } +} + export async function shutdownLogger(): Promise { if (!initialized) return diff --git a/src/core/utils/streams.ts b/src/core/utils/streams.ts index 8f519d3..092e957 100644 --- a/src/core/utils/streams.ts +++ b/src/core/utils/streams.ts @@ -1,26 +1,31 @@ -import type { Writable, Readable } from 'node:stream' - -export function nodeToWebWritable(nodeStream: Writable): WritableStream { +export function nodeToWebWritable(nodeStream: NodeJS.WritableStream): WritableStream { return new WritableStream({ write(chunk) { return new Promise((resolve, reject) => { - nodeStream.write(Buffer.from(chunk), (err) => { - if (err) reject(err) - else resolve() - }) - }) + const ok = nodeStream.write(chunk); + if (ok) { resolve(); return; } + (nodeStream as any).once("drain", resolve); + (nodeStream as any).once("error", reject); + }); }, - }) + close() { + (nodeStream as any).end(); + }, + abort(reason) { + (nodeStream as any).destroy(reason instanceof Error ? reason : new Error(String(reason))); + }, + }); } -export function nodeToWebReadable(nodeStream: Readable): ReadableStream { +export function nodeToWebReadable(nodeStream: NodeJS.ReadableStream): ReadableStream { return new ReadableStream({ start(controller) { - nodeStream.on('data', (chunk: Buffer) => { - controller.enqueue(new Uint8Array(chunk)) - }) - nodeStream.on('end', () => controller.close()) - nodeStream.on('error', (err) => controller.error(err)) + nodeStream.on("data", (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk))); + nodeStream.on("end", () => controller.close()); + nodeStream.on("error", (err) => controller.error(err)); }, - }) + cancel() { + (nodeStream as any).destroy(); + }, + }); } diff --git a/src/main.ts b/src/main.ts index ad05f6e..e391de4 100644 --- a/src/main.ts +++ b/src/main.ts @@ -268,6 +268,11 @@ export async function startServer(opts?: StartServerOptions) { core.eventBus.emit('system:ready') } catch (err) { + if (spinner) { + spinner.fail('Plugin boot failed') + spinner = undefined + } + unmuteLogger() log.error({ err }, 'Plugin boot failed') } diff --git a/src/plugins/api-server/routes/sessions.ts b/src/plugins/api-server/routes/sessions.ts index 69fd3a7..46f5d6c 100644 --- a/src/plugins/api-server/routes/sessions.ts +++ b/src/plugins/api-server/routes/sessions.ts @@ -110,8 +110,9 @@ export function registerSessionRoutes(router: Router, deps: RouteDeps): void { const channelId = adapterId ?? "api"; const resolvedAgent = agent || config.defaultAgent; + const agentDef = deps.core.agentCatalog.resolve(resolvedAgent); const resolvedWorkspace = deps.core.configManager.resolveWorkspace( - workspace || config.agents[resolvedAgent]?.workingDirectory, + workspace || agentDef?.workingDirectory, ); const session = await deps.core.createSession({ diff --git a/src/plugins/speech/__tests__/speech-tts-command.test.ts b/src/plugins/speech/__tests__/speech-tts-command.test.ts index 13d5d95..4d316b9 100644 --- a/src/plugins/speech/__tests__/speech-tts-command.test.ts +++ b/src/plugins/speech/__tests__/speech-tts-command.test.ts @@ -149,41 +149,113 @@ describe('/tts command', () => { }) describe('when TTS provider is available', () => { - async function setupWithTTS() { + function makeMockSession(id: string) { + return { + id, + voiceMode: 'off' as 'off' | 'next' | 'on', + setVoiceMode(mode: 'off' | 'next' | 'on') { + this.voiceMode = mode + }, + } + } + + function makeMockSessionManager(sessions: Map>) { + return { + getSession(id: string) { + return sessions.get(id) + }, + } + } + + async function setupWithTTS(opts?: { sessions?: Map> }) { + const sessions = opts?.sessions ?? new Map() + const sessionManager = makeMockSessionManager(sessions) + const ctx = createTestContext({ pluginName: '@openacp/speech', pluginConfig: {}, permissions: speechPlugin.permissions, }) + // Provide session manager via ctx.sessions (kernel:access) + ;(ctx as any).sessions = sessionManager + await speechPlugin.setup(ctx as any) // Retrieve the speech service and inject a TTS provider so isTTSAvailable() returns true const service = ctx.registeredServices.get('speech') as any service.registerTTSProvider('edge-tts', makeMockTTSProvider('edge-tts')) - return ctx + return { ctx, sessions, sessionManager } } it('returns text response confirming enabled when /tts on', async () => { - const ctx = await setupWithTTS() - const response = await ctx.executeCommand('tts', { raw: 'on' }) + const mockSession = makeMockSession('sess-1') + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + const response = await ctx.executeCommand('tts', { raw: 'on', sessionId: 'sess-1' }) expect(response?.type).toBe('text') expect((response as any)?.text).toMatch(/enabled/) }) it('returns text response confirming disabled when /tts off', async () => { - const ctx = await setupWithTTS() - const response = await ctx.executeCommand('tts', { raw: 'off' }) + const mockSession = makeMockSession('sess-1') + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + const response = await ctx.executeCommand('tts', { raw: 'off', sessionId: 'sess-1' }) expect(response?.type).toBe('text') expect((response as any)?.text).toMatch(/disabled/) }) - it('returns a status menu when /tts is called with no args', async () => { - const ctx = await setupWithTTS() - const response = await ctx.executeCommand('tts', { raw: '' }) + it('returns a status menu when /tts is called with no args and TTS is available', async () => { + const mockSession = makeMockSession('sess-1') + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + const response = await ctx.executeCommand('tts', { raw: '', sessionId: 'sess-1' }) // With TTS available and empty arg, falls through to the status menu expect(response?.type).toBe('menu') }) + + it('sets session voiceMode to "on" when /tts on is called with a valid sessionId', async () => { + const mockSession = makeMockSession('sess-1') + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + + await ctx.executeCommand('tts', { raw: 'on', sessionId: 'sess-1' }) + expect(mockSession.voiceMode).toBe('on') + }) + + it('sets session voiceMode to "off" when /tts off is called with a valid sessionId', async () => { + const mockSession = makeMockSession('sess-1') + mockSession.voiceMode = 'on' + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + + await ctx.executeCommand('tts', { raw: 'off', sessionId: 'sess-1' }) + expect(mockSession.voiceMode).toBe('off') + }) + + it('sets session voiceMode to "next" when /tts next is called with a valid sessionId', async () => { + const mockSession = makeMockSession('sess-1') + const sessions = new Map([['sess-1', mockSession]]) + const { ctx } = await setupWithTTS({ sessions }) + + await ctx.executeCommand('tts', { raw: 'next', sessionId: 'sess-1' }) + expect(mockSession.voiceMode).toBe('next') + }) + + it('does not crash when sessionId is null (no session context)', async () => { + const { ctx } = await setupWithTTS() + const response = await ctx.executeCommand('tts', { raw: 'on', sessionId: null }) + expect(response?.type).toBe('text') + expect((response as any)?.text).toMatch(/enabled/) + }) + + it('does not crash when session is not found for sessionId', async () => { + const { ctx } = await setupWithTTS() + const response = await ctx.executeCommand('tts', { raw: 'on', sessionId: 'nonexistent' }) + expect(response?.type).toBe('text') + expect((response as any)?.text).toMatch(/enabled/) + }) }) describe('speech service registration', () => { @@ -232,5 +304,30 @@ describe('/tts command', () => { const service = ctx.registeredServices.get('speech') as any expect(service.isSTTAvailable()).toBe(false) }) + + it('reads ttsProvider from pluginConfig instead of hardcoding edge-tts', async () => { + const ctx = createTestContext({ + pluginName: '@openacp/speech', + pluginConfig: { ttsProvider: 'custom-tts' }, + permissions: speechPlugin.permissions, + }) + await speechPlugin.setup(ctx as any) + + const service = ctx.registeredServices.get('speech') as any + // The config should reflect the custom provider name + expect(service.config.tts.provider).toBe('custom-tts') + }) + + it('defaults ttsProvider to edge-tts when not specified in pluginConfig', async () => { + const ctx = createTestContext({ + pluginName: '@openacp/speech', + pluginConfig: {}, + permissions: speechPlugin.permissions, + }) + await speechPlugin.setup(ctx as any) + + const service = ctx.registeredServices.get('speech') as any + expect(service.config.tts.provider).toBe('edge-tts') + }) }) }) diff --git a/src/plugins/speech/index.ts b/src/plugins/speech/index.ts index ff12588..5549d49 100644 --- a/src/plugins/speech/index.ts +++ b/src/plugins/speech/index.ts @@ -1,5 +1,6 @@ -import type { OpenACPPlugin, InstallContext } from '../../core/plugin/types.js' +import type { OpenACPPlugin, InstallContext, PluginContext } from '../../core/plugin/types.js' import type { OpenACPCore } from '../../core/core.js' +import type { Session } from '../../core/sessions/session.js' import { SpeechService, GroqSTT } from './exports.js' import type { SpeechServiceConfig } from './exports.js' import { installNpmPlugin } from '../../core/plugin/plugin-installer.js' @@ -144,7 +145,7 @@ const speechPlugin: OpenACPPlugin = { providers: groqApiKey ? { groq: { apiKey: groqApiKey } } : {}, }, tts: { - provider: 'edge-tts', + provider: (config.ttsProvider as string) ?? 'edge-tts', providers: {}, }, } @@ -170,16 +171,30 @@ const speechPlugin: OpenACPPlugin = { ctx.registerService('speech', service) + // Helper to look up the session and set voiceMode + const setSessionVoiceMode = (pluginCtx: PluginContext, sessionId: string | null, voiceMode: 'off' | 'next' | 'on'): void => { + if (!sessionId) return + try { + const sessionManager = pluginCtx.sessions as { getSession(id: string): Session | undefined } + const session = sessionManager.getSession(sessionId) + if (session) { + session.setVoiceMode(voiceMode) + } + } catch { + // Session lookup may fail if kernel:access is unavailable; silently ignore + } + } + ctx.registerCommand({ name: 'tts', description: 'Toggle text-to-speech', - usage: 'on|off|install', + usage: 'on|off|next|install', category: 'plugin', handler: async (args) => { const mode = args.raw.trim().toLowerCase() // Check if TTS provider is available - if ((mode === 'on' || mode === '') && !service.isTTSAvailable()) { + if ((mode === 'on' || mode === '' || mode === 'next') && !service.isTTSAvailable()) { return { type: 'menu' as const, title: 'TTS provider not installed. Install Edge TTS plugin?', @@ -215,11 +230,22 @@ const speechPlugin: OpenACPPlugin = { } } - if (mode === 'on') return { type: 'text' as const, text: 'Text-to-speech enabled' } - if (mode === 'off') return { type: 'text' as const, text: 'Text-to-speech disabled' } + if (mode === 'on') { + setSessionVoiceMode(ctx, args.sessionId, 'on') + return { type: 'text' as const, text: 'Text-to-speech enabled' } + } + if (mode === 'off') { + setSessionVoiceMode(ctx, args.sessionId, 'off') + return { type: 'text' as const, text: 'Text-to-speech disabled' } + } + if (mode === 'next') { + setSessionVoiceMode(ctx, args.sessionId, 'next') + return { type: 'text' as const, text: 'Text-to-speech enabled for next message' } + } return { type: 'menu' as const, title: 'Text to Speech', options: [ { label: 'Enable', command: '/tts on' }, { label: 'Disable', command: '/tts off' }, + { label: 'Next message only', command: '/tts next' }, ]} }, }) diff --git a/src/plugins/telegram/__tests__/activity.test.ts b/src/plugins/telegram/__tests__/activity.test.ts index 52a052a..cc66a33 100644 --- a/src/plugins/telegram/__tests__/activity.test.ts +++ b/src/plugins/telegram/__tests__/activity.test.ts @@ -65,15 +65,29 @@ describe("ThinkingIndicator", () => { expect(api.sendMessage).toHaveBeenCalledOnce(); }); - it("dismiss() clears state without calling Telegram API", async () => { + it("dismiss() deletes the Telegram message when msgId exists", async () => { await indicator.show(); - indicator.dismiss(); + await indicator.dismiss(); + expect(api.deleteMessage).toHaveBeenCalledOnce(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); + }); + + it("dismiss() does not call deleteMessage when no message was sent", async () => { + await indicator.dismiss(); expect(api.deleteMessage).not.toHaveBeenCalled(); }); + it("dismiss() swallows errors from deleteMessage", async () => { + api.deleteMessage.mockRejectedValueOnce(new Error("already deleted")); + await indicator.show(); + // Should not throw + await indicator.dismiss(); + expect(api.deleteMessage).toHaveBeenCalledOnce(); + }); + it("show() works again after dismiss() + reset()", async () => { await indicator.show(); - indicator.dismiss(); + await indicator.dismiss(); indicator.reset(); await indicator.show(); expect(api.sendMessage).toHaveBeenCalledTimes(2); @@ -81,10 +95,41 @@ describe("ThinkingIndicator", () => { it("show() is blocked after dismiss() without reset()", async () => { await indicator.show(); - indicator.dismiss(); + await indicator.dismiss(); await indicator.show(); expect(api.sendMessage).toHaveBeenCalledOnce(); }); + + it("show() deletes just-sent message if dismissed during queue wait (C17)", async () => { + // Simulate a slow queue: enqueue holds the promise until we resolve it + let resolveEnqueue!: (val: unknown) => void; + const slowQueue = { + enqueue: vi.fn( + (fn: () => Promise) => + new Promise((resolve) => { + resolveEnqueue = async () => { + const result = await fn(); + resolve(result); + }; + }), + ), + onRateLimited: vi.fn(), + } as unknown as SendQueue; + + const ind = new ThinkingIndicator(api as never, 100, 200, slowQueue); + const showPromise = ind.show(); + + // dismiss() while show() is waiting in the queue + await ind.dismiss(); + + // Now resolve the queue — sendMessage returns the message + await resolveEnqueue(undefined); + await showPromise; + + // The message was sent but should be immediately deleted + expect(api.sendMessage).toHaveBeenCalledOnce(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); + }); }); describe("ToolCard", () => { @@ -180,16 +225,16 @@ describe("ActivityTracker", () => { expect(api.sendMessage).toHaveBeenCalledOnce(); }); - it("onToolCall() dismisses thinking (no deleteMessage API call)", async () => { + it("onToolCall() dismisses thinking and deletes message", async () => { await tracker.onThought(); await tracker.onToolCall(makeMeta(), "file_read", { path: "/tmp/foo" }); - expect(api.deleteMessage).not.toHaveBeenCalled(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); }); - it("onTextStart() dismisses thinking (no deleteMessage API call)", async () => { + it("onTextStart() dismisses thinking and deletes message", async () => { await tracker.onThought(); await tracker.onTextStart(); - expect(api.deleteMessage).not.toHaveBeenCalled(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); }); it("sendUsage() is a no-op (usage is sent as separate message by adapter)", async () => { @@ -199,10 +244,10 @@ describe("ActivityTracker", () => { expect(api.sendMessage).not.toHaveBeenCalled(); }); - it("onNewPrompt() resets state", async () => { + it("onNewPrompt() dismisses thinking and deletes message", async () => { await tracker.onThought(); await tracker.onNewPrompt(); - expect(api.deleteMessage).not.toHaveBeenCalled(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); }); it("cleanup() finalizes toolCard and dismisses thinking", async () => { @@ -214,11 +259,11 @@ describe("ActivityTracker", () => { expect(true).toBe(true); }); - it("onNewPrompt() dismisses thinking without API call", async () => { + it("onNewPrompt() deletes thinking message", async () => { await tracker.onThought(); expect(api.sendMessage).toHaveBeenCalledOnce(); await tracker.onNewPrompt(); - expect(api.deleteMessage).not.toHaveBeenCalled(); + expect(api.deleteMessage).toHaveBeenCalledWith(100, 42); }); it("getToolCardMsgId() returns undefined when no tool content", () => { diff --git a/src/plugins/telegram/activity.ts b/src/plugins/telegram/activity.ts index 52ec506..16d8c06 100644 --- a/src/plugins/telegram/activity.ts +++ b/src/plugins/telegram/activity.ts @@ -44,9 +44,18 @@ export class ThinkingIndicator { disable_notification: true, }), ); - if (result && !this.dismissed) { - this.msgId = result.message_id; - this.startRefreshTimer(); + if (result) { + if (this.dismissed) { + // dismissed during queue wait — delete the just-sent message + try { + await this.api.deleteMessage(this.chatId, result.message_id); + } catch { + // Message may already be deleted + } + } else { + this.msgId = result.message_id; + this.startRefreshTimer(); + } } } catch (err) { log.warn({ err }, "ThinkingIndicator.show() failed"); @@ -55,11 +64,20 @@ export class ThinkingIndicator { } } - /** Clear state — stops refresh timer, no Telegram API call */ - dismiss(): void { + /** Dismiss indicator: stops refresh timer and deletes the Telegram message */ + async dismiss(): Promise { + if (this.dismissed) return; this.dismissed = true; - this.msgId = undefined; this.stopRefreshTimer(); + const msgId = this.msgId; + this.msgId = undefined; + if (msgId) { + try { + await this.api.deleteMessage(this.chatId, msgId); + } catch { + // Message may already be deleted + } + } } /** Reset for a new prompt cycle */ @@ -241,7 +259,7 @@ export class ActivityTracker { async onNewPrompt(): Promise { this.isFirstEvent = true; - this.thinking.dismiss(); + await this.thinking.dismiss(); this.thinking.reset(); // Finalize old tool card (flush pending state) and create a fresh one @@ -265,7 +283,7 @@ export class ActivityTracker { async onTextStart(): Promise { this.isFirstEvent = false; - this.thinking.dismiss(); + await this.thinking.dismiss(); // If tool card has content, finalize it — text interrupts the tool sequence await this.sealToolCardIfNeeded(); } @@ -276,7 +294,7 @@ export class ActivityTracker { rawInput: unknown, ): Promise { this.isFirstEvent = false; - this.thinking.dismiss(); + await this.thinking.dismiss(); this.thinking.reset(); this.toolCard.addTool(meta, kind, rawInput); } @@ -305,7 +323,7 @@ export class ActivityTracker { async onPlan(entries: PlanEntry[]): Promise { this.isFirstEvent = false; - this.thinking.dismiss(); + await this.thinking.dismiss(); this.toolCard.updatePlan(entries); } @@ -323,13 +341,13 @@ export class ActivityTracker { } async cleanup(): Promise { - this.thinking.dismiss(); + await this.thinking.dismiss(); await this.toolCard.finalize(); this.toolCard.destroy(); } destroy(): void { - this.thinking.dismiss(); + void this.thinking.dismiss(); this.toolCard.destroy(); } } diff --git a/src/plugins/telegram/adapter.ts b/src/plugins/telegram/adapter.ts index e32bd86..2979193 100644 --- a/src/plugins/telegram/adapter.ts +++ b/src/plugins/telegram/adapter.ts @@ -1355,17 +1355,19 @@ export class TelegramAdapter extends MessagingAdapter { await this.skillManager.cleanup(sessionId); } - async archiveSessionTopic(sessionId: string): Promise { + async stripTTSBlock(sessionId: string): Promise { + await this.draftManager.stripPattern(sessionId, /\[TTS\][\s\S]*?\[\/TTS\]/g); + } + + async archiveSessionTopic(sessionId: string): Promise { const core = this.core as OpenACPCore; const session = core.sessionManager.getSession(sessionId); - if (!session) return; + if (!session) throw new Error("Session not found"); const chatId = this.telegramConfig.chatId; const oldTopicId = Number(session.threadId); - // Strip existing 🔄 prefix to avoid stacking on repeated archives // Set archiving flag — sendMessage will skip while this is true. - // Flag stays true until core finishes cancelSession (prevents race window). session.archiving = true; // Finalize any pending draft @@ -1380,7 +1382,16 @@ export class TelegramAdapter extends MessagingAdapter { this.sessionTrackers.delete(session.id); } - // Delete topic (removes all messages) + // 1. Delete old topic (removes all messages) await deleteSessionTopic(this.bot, chatId, oldTopicId); + + // 2. Create new topic with session name + const topicName = session.name ?? `Session ${session.id.slice(0, 6)}`; + const newTopicId = await createSessionTopic(this.bot, chatId, topicName); + + // Clear archiving flag — messages can now be sent to new topic + session.archiving = false; + + return String(newTopicId); } } diff --git a/src/plugins/telegram/commands/resume.ts b/src/plugins/telegram/commands/resume.ts index 0d24a14..f34341a 100644 --- a/src/plugins/telegram/commands/resume.ts +++ b/src/plugins/telegram/commands/resume.ts @@ -210,6 +210,9 @@ async function executeResume( parse_mode: "HTML", }); + // TODO: Over-budget interactive selection not yet implemented (F7) + // Spec says: show options when context > 30K tokens, auto-select after 60s + const { session, contextResult } = await core.createSessionWithContext({ channelId: "telegram", agentName, diff --git a/src/plugins/telegram/commands/session.ts b/src/plugins/telegram/commands/session.ts index b58f841..e350fac 100644 --- a/src/plugins/telegram/commands/session.ts +++ b/src/plugins/telegram/commands/session.ts @@ -365,16 +365,32 @@ export async function handleArchive( // Check in-memory session first, then fall back to stored record const session = core.sessionManager.getSessionByThread("telegram", String(threadId)); const record = !session ? core.sessionManager.getRecordByThread("telegram", String(threadId)) : undefined; - // Use sessionId if available, otherwise use threadId as identifier for orphan topics - const identifier = session?.id ?? record?.sessionId ?? `topic:${threadId}`; + + // Must be used in a session topic (not orphan or non-session) + if (!session && !record) { + await ctx.reply("This topic is not linked to a session.", { parse_mode: "HTML" }); + return; + } + + const identifier = session?.id ?? record?.sessionId; + if (!identifier) { + await ctx.reply("Could not determine session for this topic.", { parse_mode: "HTML" }); + return; + } + + // Session must be active (not initializing) + const status = session?.status ?? record?.status; + if (status === "initializing") { + await ctx.reply("Cannot archive a session that is still initializing. Wait for it to become active.", { parse_mode: "HTML" }); + return; + } await ctx.reply( "⚠️ Archive this session?\n\n" + "This will:\n" + - "• Delete this topic and all messages\n" + - "• Stop the agent session (if running)\n" + - "• Remove the session record\n\n" + - "This action cannot be undone.", + "• Delete this topic and recreate it (clearing chat history)\n" + + "• The agent session will keep running\n\n" + + "Chat history cannot be recovered.", { parse_mode: "HTML", reply_markup: new InlineKeyboard() @@ -396,7 +412,7 @@ export async function handleArchiveConfirm( await ctx.answerCallbackQuery(); } catch { /* expired */ } - // Format: ar:: where identifier is sessionId or topic: + // Format: ar:: where identifier is sessionId const [, action, ...rest] = data.split(":"); const identifier = rest.join(":"); @@ -406,40 +422,25 @@ export async function handleArchiveConfirm( } // action === "yes" - await ctx.editMessageText("🔄 Archiving...", { parse_mode: "HTML" }); - - // Handle orphan topics (no session/record) — delete topic directly - if (identifier.startsWith("topic:")) { - const topicId = Number(identifier.slice("topic:".length)); - try { - await ctx.api.deleteForumTopic(chatId, topicId); - core.notificationManager.notifyAll({ - sessionId: "system", - sessionName: `Orphan topic #${topicId}`, - type: "completed", - summary: `Orphan topic #${topicId} archived and deleted.`, - }); - } catch (err) { - core.notificationManager.notifyAll({ - sessionId: "system", - sessionName: `Orphan topic #${topicId}`, - type: "error", - summary: `Failed to delete orphan topic #${topicId}: ${(err as Error).message}`, - }); - } - return; - } + // Note: we don't editMessageText here because the topic is about to be deleted const result = await core.archiveSession(identifier); if (result.ok) { - core.notificationManager.notifyAll({ - sessionId: identifier, - type: "completed", - summary: `Session archived and deleted.`, - }); + // Send confirmation in the new topic + const adapter = core.adapters.get("telegram"); + if (adapter) { + try { + await adapter.sendMessage(identifier, { + type: "text", + text: "Chat history cleared. Session is still active — send a message to continue.", + }); + } catch { + // Best effort — the new topic is already created + } + } } else { try { - await ctx.editMessageText(`❌ Failed to archive: ${escapeHtml(result.error)}`, { parse_mode: "HTML" }); + await ctx.editMessageText(`Failed to archive: ${escapeHtml(result.error)}`, { parse_mode: "HTML" }); } catch { core.notificationManager.notifyAll({ sessionId: identifier, diff --git a/src/plugins/telegram/draft-manager.ts b/src/plugins/telegram/draft-manager.ts index 29c7ae7..6165428 100644 --- a/src/plugins/telegram/draft-manager.ts +++ b/src/plugins/telegram/draft-manager.ts @@ -7,9 +7,15 @@ import { buildActionKeyboard, } from "./action-detect.js"; +interface FinalizedDraft { + messageId: number; + draft: MessageDraft; +} + export class DraftManager { private drafts: Map = new Map(); private textBuffers: Map = new Map(); + private finalizedDrafts: Map = new Map(); constructor( private bot: Bot, @@ -63,6 +69,11 @@ export class DraftManager { this.drafts.delete(sessionId); const finalMsgId = await draft.finalize(); + // Keep finalized draft reference so tts_strip can edit after finalization + if (finalMsgId) { + this.finalizedDrafts.set(sessionId, { messageId: finalMsgId, draft }); + } + // Detect actions in assistant responses and attach keyboard if (assistantSessionId && sessionId === assistantSessionId) { const fullText = this.textBuffers.get(sessionId); @@ -88,8 +99,27 @@ export class DraftManager { } } + /** + * Strip a regex pattern from the active or finalized draft for a session. + * Used by tts_strip to remove [TTS]...[/TTS] blocks after TTS audio is sent. + */ + async stripPattern(sessionId: string, pattern: RegExp): Promise { + const draft = this.drafts.get(sessionId); + if (draft) { + await draft.stripPattern(pattern); + return; + } + const finalized = this.finalizedDrafts.get(sessionId); + if (finalized) { + await finalized.draft.stripPattern(pattern); + } + // If no draft found (e.g., TTS synthesis slower than next prompt cycle), the + // [TTS] block will remain visible. This is a rare edge case — log for debugging. + } + cleanup(sessionId: string): void { this.drafts.delete(sessionId); this.textBuffers.delete(sessionId); + this.finalizedDrafts.delete(sessionId); } } diff --git a/src/plugins/tunnel/index.ts b/src/plugins/tunnel/index.ts index 927ac70..bc85f5d 100644 --- a/src/plugins/tunnel/index.ts +++ b/src/plugins/tunnel/index.ts @@ -142,11 +142,39 @@ function createTunnelPlugin(): OpenACPPlugin { ctx.registerCommand({ name: 'tunnel', - description: 'Show tunnel status and URL', + description: 'Manage tunnels: /tunnel [label] | /tunnel stop ', category: 'plugin', - handler: async () => { + handler: async (args) => { + const parts = args.raw.trim().split(/\s+/) + + // /tunnel stop + if (parts[0] === 'stop' && parts[1]) { + const port = parseInt(parts[1], 10) + if (isNaN(port)) return { type: 'error', message: 'Invalid port number' } + try { + await tunnelSvc.stopTunnel(port) + return { type: 'text', text: `Tunnel on port ${port} stopped.` } + } catch (err) { + return { type: 'error', message: (err as Error).message } + } + } + + // /tunnel [label] + if (parts[0] && parts[0] !== '') { + const port = parseInt(parts[0], 10) + if (isNaN(port)) return { type: 'error', message: 'Invalid port number' } + const label = parts.slice(1).join(' ') || undefined + try { + const entry = await tunnelSvc.addTunnel(port, { label }) + return { type: 'text', text: `Tunnel created: ${entry.publicUrl ?? 'starting...'}` } + } catch (err) { + return { type: 'error', message: (err as Error).message } + } + } + + // /tunnel (no args) — show current tunnel URL const url = tunnelSvc.getPublicUrl() - return { type: 'text', text: `Tunnel active: ${url}` } + return { type: 'text', text: url ? `Tunnel: ${url}` : 'No tunnel active.' } }, }) @@ -155,10 +183,16 @@ function createTunnelPlugin(): OpenACPPlugin { description: 'List active tunnels', category: 'plugin', handler: async () => { - const url = tunnelSvc.getPublicUrl() - return { type: 'list', title: 'Active Tunnels', items: [ - { label: 'Primary', detail: url }, - ]} + const userTunnels = tunnelSvc.listTunnels() + const systemUrl = tunnelSvc.getPublicUrl() + const items = [ + { label: 'System', detail: systemUrl }, + ...userTunnels.map(t => ({ + label: t.label ?? `Port ${t.port}`, + detail: `${t.publicUrl ?? t.status} (${t.provider})`, + })), + ] + return { type: 'list', title: 'Active Tunnels', items } }, })