From 9038102d46d8781a5e1512ca493bfe57f6415c0d Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:10:21 +0700 Subject: [PATCH 1/7] fix: critical code fixes from codebase logic review Session state machine: - Guard processPrompt for finished state (prevents double-throw crash) - Add cancelled to valid transitions from error state - Wrap abortPrompt in try-catch in cancelSession (agent may be dead) - Set session.threadId before createSession in lazy resume - Skip cancelled sessions in lazy resume (spawn fresh instead) - Backup corrupt sessions.json as .bak before starting empty Error handling & stability: - Validate config before writing to disk (prevents bricking on restart) - Close session logger file descriptors on destroy - Clean up spinner/logger on plugin boot failure - Catch sendMessage middleware errors (prevent unhandled rejections) - Unref permission gate timeout timer (unblock graceful shutdown) Adapter primitives: - Remove thinking indicator on maxThinkingDuration exceeded - Remove draft from map after finalize in shared DraftManager - ToolCardState appendUsage uses scheduleFlush instead of immediate flush - Node stream adapters: add close/cancel/abort handlers CLI/API field fixes: - Fix CLI api session field access (.session wrapper + correct field names) - Fix CLI api health field access (uptime in ms, memory.rss, tunnel object) - Use AgentCatalog.resolve() in API sessions route instead of config.agents TTS: - Move voiceMode "next" reset after successful prompt (preserve on error) --- .../plans/2026-03-28-critical-code-fixes.md | 992 ++++++++++++++++++ ...26-03-28-codebase-logic-review-findings.md | 316 ++++++ src/__tests__/api-server.test.ts | 3 + src/cli/commands/api.ts | 37 +- .../__tests__/activity-tracker.test.ts | 32 + .../__tests__/draft-manager.test.ts | 23 + .../__tests__/tool-card-state.test.ts | 3 +- .../primitives/activity-tracker.ts | 2 + .../primitives/draft-manager.ts | 1 + .../primitives/tool-card-state.ts | 2 +- src/core/config/config.ts | 12 +- src/core/core.ts | 11 +- .../__tests__/session-comprehensive.test.ts | 7 +- .../__tests__/session-lifecycle.test.ts | 11 + .../__tests__/session-manager.test.ts | 12 + .../__tests__/session-state-machine.test.ts | 14 +- .../sessions/__tests__/session-tts.test.ts | 19 + src/core/sessions/permission-gate.ts | 3 + src/core/sessions/session-bridge.ts | 26 +- src/core/sessions/session-manager.ts | 6 +- src/core/sessions/session-store.ts | 5 +- src/core/sessions/session.ts | 15 +- src/core/utils/log.ts | 7 + src/core/utils/streams.ts | 37 +- src/main.ts | 5 + src/plugins/api-server/routes/sessions.ts | 3 +- 26 files changed, 1535 insertions(+), 69 deletions(-) create mode 100644 docs/superpowers/plans/2026-03-28-critical-code-fixes.md create mode 100644 docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md create mode 100644 src/core/adapter-primitives/__tests__/activity-tracker.test.ts create mode 100644 src/core/adapter-primitives/__tests__/draft-manager.test.ts 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..d3e52ce --- /dev/null +++ b/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md @@ -0,0 +1,316 @@ +# 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. Summary & Priority + +## Fix Priority + +### Batch 1 — Quick code fixes (1-5 lines each) +1. **C1** — Guard processPrompt for finished state +2. **C2** — Add cancelled to error transitions +3. **C5** — Remove thinking indicator on timeout +4. **F9** — Move voiceMode "next" reset after successful prompt +5. **C8** — Unref permission gate timer +6. **C13** — Wrap abortPrompt in try-catch in cancelSession (agent may be dead) +7. **C16** — Remove draft from map after finalize in shared DraftManager + +### Batch 2 — Session lifecycle fixes +8. **C12** — Set session.threadId BEFORE createSession in lazy resume (events dropped during spawn) +9. **F1+F2** — Fix lazy resume: skip cancelled, fallback to fresh on failure +10. **C15** — Backup corrupt sessions.json as .bak before starting empty + +### Batch 3 — API/CLI field mismatches +11. **F19** — Fix CLI api session field access (.session wrapper + field names) +12. **F20** — Fix CLI api health field access (uptime, memory) +13. **F21** — Use AgentCatalog.resolve() in API sessions route + +### Batch 4 — Broken features +14. **F3+F4** — Rewrite /archive: keep agent alive + recreate topic +15. **F11+F12** — Fix /tts to set voiceMode + read config +16. **F18** — Create usage plugin (UsageStore + UsageBudget + /usage command) +17. **F13** — ThinkingIndicator dismiss() should delete message +18. **C17** — ThinkingIndicator: delete message if dismissed during queue wait + +### Batch 5 — Error handling & stability +19. **C3** — Validate config before writing to disk +20. **C4** — Close session logger file descriptors +21. **C6** — Clean up spinner/logger on boot failure +22. **C9** — Catch sendMessage middleware errors +23. **C14** — ToolCardState appendUsage: use scheduleFlush instead of immediate flush + +### Batch 6 — Missing features +24. **F10** — Implement tts_strip event +25. **F7** — Over-budget interactive selection for /resume +26. **F22** — Settings validation at boot +27. **F24** — Telegram /tunnel create/stop commands + +### Batch 6 — Test coverage +22. **T1** — Lazy resume tests +23. **T3** — API route handler tests +24. **T5** — Tunnel tests +25. **T6** — Telegram command handler tests 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/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/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..195379b 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -308,10 +308,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 +628,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,6 +659,7 @@ export class OpenACPCore { resumeAgentSessionId: record.agentSessionId, existingSessionId: record.sessionId, initialName: record.name, + threadId: message.threadId, }); session.threadId = message.threadId; session.activate(); 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..84e2726 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"); } } 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..d236851 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); @@ -500,5 +504,6 @@ export class Session extends TypedEmitter { // Clear queued prompts this.queue.clear(); await this.agentInstance.destroy(); + closeSessionLogger(this.log); } } 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({ From 270ab52ba2328a752d749d0988158fc0b0a18892 Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:16:01 +0700 Subject: [PATCH 2/7] fix: TTS voiceMode, ThinkingIndicator cleanup, settings validation TTS fixes (F11+F12): - /tts command now sets session voiceMode via kernel:access - /tts on/off/next all work across adapters (not just Telegram) - ttsProvider read from plugin config instead of hardcoded edge-tts ThinkingIndicator fixes (F13+C17): - dismiss() now deletes the Telegram message instead of just clearing state - show() deletes just-sent message if dismissed during SendQueue wait Plugin system (F22): - Settings validation against settingsSchema enforced at boot - Invalid settings prevent plugin from booting (marked as failed) --- .../__tests__/lifecycle-migration.test.ts | 150 ++++++++++++++++++ src/core/plugin/lifecycle-manager.ts | 11 ++ .../__tests__/speech-tts-command.test.ts | 115 ++++++++++++-- src/plugins/speech/index.ts | 38 ++++- .../telegram/__tests__/activity.test.ts | 69 ++++++-- src/plugins/telegram/activity.ts | 42 +++-- 6 files changed, 386 insertions(+), 39 deletions(-) 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/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(); } } From 18c590d7192104ef13f685f1a6c8425d76dc78a4 Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:20:58 +0700 Subject: [PATCH 3/7] fix: archive topic recreation and tts_strip event MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Archive rewrite (F3+F4): - Archive now keeps agent alive and recreates topic instead of killing session - Flow: delete old topic → create new topic → rewire session.threadId - Session stays in memory and store with updated topicId - Validates session state (must be active, not initializing) - Rejects non-session topics with guidance message - Tests updated to verify new behavior TTS strip (F10): - Add tts_strip AgentEvent type - Emit tts_strip after successful TTS synthesis - SessionBridge dispatches to adapter.stripTTSBlock() - Telegram DraftManager retains finalized drafts for post-finalize strip - [TTS]...[/TTS] block removed from visible message after audio sent --- src/__tests__/archive-session.test.ts | 107 +++++++++++++---------- src/core/channel.ts | 7 +- src/core/core.ts | 54 +++++------- src/core/sessions/session-bridge.ts | 4 + src/core/sessions/session.ts | 1 + src/core/types.ts | 3 +- src/plugins/telegram/adapter.ts | 21 +++-- src/plugins/telegram/commands/session.ts | 73 ++++++++-------- src/plugins/telegram/draft-manager.ts | 28 ++++++ 9 files changed, 177 insertions(+), 121 deletions(-) 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/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/core.ts b/src/core/core.ts index 195379b..b49a4b5 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -186,47 +186,39 @@ 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); + // archiveSessionTopic handles: cleanup trackers → delete old topic → create new topic + const newThreadId = await adapter.archiveSessionTopic(session.id); + + // Rewire session to new topic + session.threadId = newThreadId; + + // Update session store with new topic ID + const platform: Record = {}; + if (session.channelId === "telegram") { + platform.topicId = Number(newThreadId); } else { - await adapter.deleteSessionThread?.(sessionId); + platform.threadId = newThreadId; } + await this.sessionManager.patchRecord(sessionId, { platform }); - // 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; - } - } - - // 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 }; } } diff --git a/src/core/sessions/session-bridge.ts b/src/core/sessions/session-bridge.ts index 84e2726..826b523 100644 --- a/src/core/sessions/session-bridge.ts +++ b/src/core/sessions/session-bridge.ts @@ -268,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.ts b/src/core/sessions/session.ts index d236851..2fdf62b 100644 --- a/src/core/sessions/session.ts +++ b/src/core/sessions/session.ts @@ -354,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!); 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/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/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..eb41297 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,25 @@ 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); + } + } + cleanup(sessionId: string): void { this.drafts.delete(sessionId); this.textBuffers.delete(sessionId); + this.finalizedDrafts.delete(sessionId); } } From 0bc34ca93e2e9bebbeacab8866e430bf6eb8802d Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:28:00 +0700 Subject: [PATCH 4/7] feat: usage tracking plugin and tunnel command improvements Usage plugin (F18): - Create src/plugins/usage/ with UsageStore, UsageBudget - Listen to usage:recorded events, buffer with debounced flush - Budget checking with warning/exceeded notifications (dedup) - /usage command showing monthly spending summary - 26 tests for store and budget logic - Registered in core-plugins Tunnel commands (F24): - /tunnel [label] creates user tunnels - /tunnel stop stops user tunnels - /tunnels lists all active tunnels with details Resume (F7): - Added TODO for over-budget interactive selection --- src/plugins/core-plugins.ts | 2 + src/plugins/telegram/commands/resume.ts | 3 + src/plugins/tunnel/index.ts | 48 +++- .../usage/__tests__/usage-budget.test.ts | 208 ++++++++++++++++++ .../usage/__tests__/usage-store.test.ts | 198 +++++++++++++++++ src/plugins/usage/index.ts | 193 ++++++++++++++++ src/plugins/usage/usage-budget.ts | 72 ++++++ src/plugins/usage/usage-store.ts | 89 ++++++++ 8 files changed, 806 insertions(+), 7 deletions(-) create mode 100644 src/plugins/usage/__tests__/usage-budget.test.ts create mode 100644 src/plugins/usage/__tests__/usage-store.test.ts create mode 100644 src/plugins/usage/index.ts create mode 100644 src/plugins/usage/usage-budget.ts create mode 100644 src/plugins/usage/usage-store.ts diff --git a/src/plugins/core-plugins.ts b/src/plugins/core-plugins.ts index a05682f..d81eabf 100644 --- a/src/plugins/core-plugins.ts +++ b/src/plugins/core-plugins.ts @@ -8,6 +8,7 @@ import fileServicePlugin from './file-service/index.js' import contextPlugin from './context/index.js' import speechPlugin from './speech/index.js' import notificationsPlugin from './notifications/index.js' +import usagePlugin from './usage/index.js' import tunnelPlugin from './tunnel/index.js' import apiServerPlugin from './api-server/index.js' import telegramPlugin from './telegram/index.js' @@ -19,6 +20,7 @@ export const corePlugins = [ contextPlugin, speechPlugin, notificationsPlugin, + usagePlugin, // Infrastructure plugins tunnelPlugin, apiServerPlugin, 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/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 } }, }) diff --git a/src/plugins/usage/__tests__/usage-budget.test.ts b/src/plugins/usage/__tests__/usage-budget.test.ts new file mode 100644 index 0000000..b43ac64 --- /dev/null +++ b/src/plugins/usage/__tests__/usage-budget.test.ts @@ -0,0 +1,208 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { UsageBudget } from '../usage-budget.js' +import type { UsagePluginConfig } from '../usage-budget.js' +import { UsageStore } from '../usage-store.js' +import type { PluginStorage } from '../../../core/plugin/types.js' + +function mockStorage(): PluginStorage { + const data = new Map() + return { + get: vi.fn(async (key: string) => data.get(key) as T | undefined), + set: vi.fn(async (key: string, value: T) => { data.set(key, value) }), + delete: vi.fn(async (key: string) => { data.delete(key) }), + list: vi.fn(async () => [...data.keys()]), + getDataDir: vi.fn(() => '/tmp/usage-test'), + } +} + +function makeRecord(cost: number) { + return { + id: `rec-${Math.random()}`, + sessionId: 'sess-1', + agentName: 'claude', + tokensUsed: 1000, + contextSize: 5000, + cost: { amount: cost, currency: 'USD' }, + timestamp: new Date().toISOString(), + } +} + +describe('UsageBudget', () => { + let store: UsageStore + let storage: PluginStorage + + beforeEach(() => { + vi.useFakeTimers() + storage = mockStorage() + store = new UsageStore(storage) + }) + + afterEach(() => { + store.destroy() + vi.useRealTimers() + }) + + describe('check', () => { + it('returns ok when no budget is set', async () => { + const budget = new UsageBudget(store, { monthlyBudget: 0 }) + const result = budget.check() + expect(result.status).toBe('ok') + expect(result.message).toBeUndefined() + }) + + it('returns ok when spending is below threshold', async () => { + await store.append(makeRecord(5.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) + + const result = budget.check() + expect(result.status).toBe('ok') + expect(result.message).toBeUndefined() + }) + + it('returns warning when threshold is crossed', async () => { + await store.append(makeRecord(85.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) + + const result = budget.check() + expect(result.status).toBe('warning') + expect(result.message).toContain('Budget warning') + expect(result.message).toContain('$85.00') + expect(result.message).toContain('$100.00') + expect(result.message).toContain('85%') + }) + + it('returns exceeded when budget is exceeded', async () => { + await store.append(makeRecord(110.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) + + const result = budget.check() + expect(result.status).toBe('exceeded') + expect(result.message).toContain('Budget exceeded') + expect(result.message).toContain('$110.00') + }) + + it('deduplicates notifications - only notifies on status change', async () => { + const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } + + await store.append(makeRecord(85.00)) + const budget = new UsageBudget(store, config) + + // First check: warning with message + const first = budget.check() + expect(first.status).toBe('warning') + expect(first.message).toBeDefined() + + // Second check at same level: no message + const second = budget.check() + expect(second.status).toBe('warning') + expect(second.message).toBeUndefined() + }) + + it('escalates from warning to exceeded', async () => { + const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } + + await store.append(makeRecord(85.00)) + const budget = new UsageBudget(store, config) + + const warning = budget.check() + expect(warning.status).toBe('warning') + expect(warning.message).toBeDefined() + + // Add more cost to exceed budget + await store.append(makeRecord(20.00)) + + const exceeded = budget.check() + expect(exceeded.status).toBe('exceeded') + expect(exceeded.message).toContain('Budget exceeded') + }) + + it('resets notification tracking on month boundary', async () => { + const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } + + await store.append(makeRecord(85.00)) + const budget = new UsageBudget(store, config) + + // Trigger warning + const first = budget.check() + expect(first.message).toBeDefined() + + // Simulate month change by advancing time + const nextMonth = new Date() + nextMonth.setMonth(nextMonth.getMonth() + 1) + vi.setSystemTime(nextMonth) + + // Add usage in new month + await store.append(makeRecord(85.00)) + + // Should get a new warning since month changed + const afterReset = budget.check() + expect(afterReset.status).toBe('warning') + expect(afterReset.message).toBeDefined() + }) + }) + + describe('getStatus', () => { + it('returns status with zero budget', () => { + const budget = new UsageBudget(store, { monthlyBudget: 0 }) + const status = budget.getStatus() + expect(status.status).toBe('ok') + expect(status.used).toBe(0) + expect(status.budget).toBe(0) + expect(status.percent).toBe(0) + }) + + it('returns correct percentage', async () => { + await store.append(makeRecord(25.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + + const status = budget.getStatus() + expect(status.status).toBe('ok') + expect(status.used).toBeCloseTo(25.00) + expect(status.budget).toBe(100) + expect(status.percent).toBe(25) + }) + + it('returns warning status at threshold', async () => { + await store.append(makeRecord(80.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) + + const status = budget.getStatus() + expect(status.status).toBe('warning') + }) + + it('returns exceeded status over budget', async () => { + await store.append(makeRecord(120.00)) + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + + const status = budget.getStatus() + expect(status.status).toBe('exceeded') + expect(status.percent).toBe(120) + }) + }) + + describe('progressBar', () => { + it('renders correct bar at 50%', () => { + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + const bar = budget.progressBar(0.5) + expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591') + }) + + it('renders full bar at 100%', () => { + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + const bar = budget.progressBar(1.0) + expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') + }) + + it('caps bar at 10 filled blocks for values over 100%', () => { + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + const bar = budget.progressBar(1.5) + expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') + }) + + it('renders empty bar at 0%', () => { + const budget = new UsageBudget(store, { monthlyBudget: 100 }) + const bar = budget.progressBar(0) + expect(bar).toBe('\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591') + }) + }) +}) diff --git a/src/plugins/usage/__tests__/usage-store.test.ts b/src/plugins/usage/__tests__/usage-store.test.ts new file mode 100644 index 0000000..b4e67e3 --- /dev/null +++ b/src/plugins/usage/__tests__/usage-store.test.ts @@ -0,0 +1,198 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { UsageStore } from '../usage-store.js' +import type { PluginStorage } from '../../../core/plugin/types.js' +import type { UsageRecord } from '../../../core/types.js' + +function mockStorage(): PluginStorage { + const data = new Map() + return { + get: vi.fn(async (key: string) => data.get(key) as T | undefined), + set: vi.fn(async (key: string, value: T) => { data.set(key, value) }), + delete: vi.fn(async (key: string) => { data.delete(key) }), + list: vi.fn(async () => [...data.keys()]), + getDataDir: vi.fn(() => '/tmp/usage-test'), + } +} + +function makeRecord(overrides: Partial = {}): UsageRecord { + return { + id: 'rec-1', + sessionId: 'sess-1', + agentName: 'claude', + tokensUsed: 1000, + contextSize: 5000, + cost: { amount: 0.05, currency: 'USD' }, + timestamp: new Date().toISOString(), + ...overrides, + } +} + +describe('UsageStore', () => { + let storage: PluginStorage + let store: UsageStore + + beforeEach(() => { + vi.useFakeTimers() + storage = mockStorage() + store = new UsageStore(storage) + }) + + afterEach(() => { + store.destroy() + vi.useRealTimers() + }) + + describe('append', () => { + it('adds record to in-memory cache', async () => { + const record = makeRecord() + await store.append(record) + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBe(0.05) + expect(total.currency).toBe('USD') + }) + + it('loads from storage on first append for a new month key', async () => { + const existing = makeRecord({ id: 'old-1', cost: { amount: 0.10, currency: 'USD' } }) + const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` + await storage.set(key, [existing]) + + await store.append(makeRecord({ id: 'new-1' })) + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBeCloseTo(0.15) + }) + + it('schedules debounced flush', async () => { + await store.append(makeRecord()) + expect(storage.set).not.toHaveBeenCalledWith(expect.stringContaining('records:'), expect.anything()) + + vi.advanceTimersByTime(2000) + await vi.waitFor(() => { + expect(storage.set).toHaveBeenCalled() + }) + }) + }) + + describe('getMonthlyTotal', () => { + it('returns zero for empty cache', () => { + const total = store.getMonthlyTotal() + expect(total.totalCost).toBe(0) + expect(total.currency).toBe('USD') + }) + + it('sums costs across multiple records', async () => { + await store.append(makeRecord({ id: '1', cost: { amount: 0.10, currency: 'USD' } })) + await store.append(makeRecord({ id: '2', cost: { amount: 0.25, currency: 'USD' } })) + await store.append(makeRecord({ id: '3', cost: { amount: 0.05, currency: 'USD' } })) + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBeCloseTo(0.40) + }) + + it('handles records without cost', async () => { + await store.append(makeRecord({ id: '1', cost: undefined })) + await store.append(makeRecord({ id: '2', cost: { amount: 0.10, currency: 'USD' } })) + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBeCloseTo(0.10) + }) + + it('returns totals for specific month', async () => { + await store.append(makeRecord({ id: '1', timestamp: '2026-01-15T00:00:00Z', cost: { amount: 0.50, currency: 'USD' } })) + await store.append(makeRecord({ id: '2', timestamp: '2026-02-15T00:00:00Z', cost: { amount: 0.30, currency: 'USD' } })) + + const janTotal = store.getMonthlyTotal(new Date('2026-01-15')) + expect(janTotal.totalCost).toBeCloseTo(0.50) + + const febTotal = store.getMonthlyTotal(new Date('2026-02-15')) + expect(febTotal.totalCost).toBeCloseTo(0.30) + }) + }) + + describe('flush', () => { + it('writes all dirty keys to storage', async () => { + await store.append(makeRecord()) + await store.flush() + + const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` + expect(storage.set).toHaveBeenCalledWith(key, expect.any(Array)) + }) + + it('clears dirty set after flush', async () => { + await store.append(makeRecord()); + + // Reset mock to track only flush calls + (storage.set as ReturnType).mockClear() + + await store.flush() + expect(storage.set).toHaveBeenCalledTimes(1); + + // Second flush should not write again + (storage.set as ReturnType).mockClear() + await store.flush() + expect(storage.set).not.toHaveBeenCalled() + }) + + it('cancels pending debounced flush', async () => { + await store.append(makeRecord()) + + // Manually flush — this should clear the pending debounce timer + // and write all dirty keys to storage + store.flush() + + // Advance past the debounce period and verify no extra writes occur + const setCalls = (storage.set as ReturnType).mock.calls.length + vi.advanceTimersByTime(5000) + + // No additional set calls beyond what flush() already did + expect((storage.set as ReturnType).mock.calls.length).toBe(setCalls) + }) + }) + + describe('loadFromStorage', () => { + it('loads current month records into cache', async () => { + const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` + const existing = [makeRecord({ id: 'stored-1', cost: { amount: 1.00, currency: 'USD' } })] + await storage.set(key, existing) + + await store.loadFromStorage() + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBeCloseTo(1.00) + }) + + it('handles empty storage gracefully', async () => { + await store.loadFromStorage() + + const total = store.getMonthlyTotal() + expect(total.totalCost).toBe(0) + }) + }) + + describe('cleanupExpired', () => { + it('deletes records older than retention period', async () => { + // Store old records under a key from 6 months ago + await storage.set('records:2025-01', [makeRecord()]) + await storage.set('records:2025-06', [makeRecord()]) + // Current month should stay + const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` + await storage.set(currentKey, [makeRecord()]) + + await store.cleanupExpired(90) + + expect(storage.delete).toHaveBeenCalledWith('records:2025-01') + expect(storage.delete).toHaveBeenCalledWith('records:2025-06') + expect(storage.delete).not.toHaveBeenCalledWith(currentKey) + }) + + it('does nothing when no expired keys exist', async () => { + const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` + await storage.set(currentKey, [makeRecord()]) + + await store.cleanupExpired(90) + + expect(storage.delete).not.toHaveBeenCalled() + }) + }) +}) diff --git a/src/plugins/usage/index.ts b/src/plugins/usage/index.ts new file mode 100644 index 0000000..88288aa --- /dev/null +++ b/src/plugins/usage/index.ts @@ -0,0 +1,193 @@ +import { nanoid } from 'nanoid' +import type { OpenACPPlugin, InstallContext, NotificationService } from '../../core/plugin/types.js' +import type { UsageRecordEvent, UsageRecord } from '../../core/types.js' +import { UsageStore } from './usage-store.js' +import { UsageBudget } from './usage-budget.js' +import type { UsagePluginConfig } from './usage-budget.js' + +function createUsagePlugin(): OpenACPPlugin { + let store: UsageStore | undefined + + return { + name: '@openacp/usage', + version: '1.0.0', + description: 'Token usage tracking and budget enforcement', + essential: false, + optionalPluginDependencies: { '@openacp/notifications': '^1.0.0' }, + permissions: [ + 'events:read', + 'services:register', + 'services:use', + 'commands:register', + 'storage:read', + 'storage:write', + ], + + async setup(ctx) { + const config: UsagePluginConfig = { + monthlyBudget: (ctx.pluginConfig.monthlyBudget as number | undefined) ?? 0, + warningThreshold: (ctx.pluginConfig.warningThreshold as number | undefined) ?? 0.8, + retentionDays: (ctx.pluginConfig.retentionDays as number | undefined) ?? 90, + } + + store = new UsageStore(ctx.storage) + const budget = new UsageBudget(store, config) + + // Load existing records into memory cache + await store.loadFromStorage() + + // Clean old records on startup + await store.cleanupExpired(config.retentionDays ?? 90) + + // Listen to usage events from core + ctx.on('usage:recorded', ((...args: unknown[]) => { + const record = args[0] as UsageRecordEvent + const usageRecord: UsageRecord = { + id: nanoid(), + sessionId: record.sessionId, + agentName: record.agentName, + timestamp: record.timestamp, + tokensUsed: record.tokensUsed, + contextSize: record.contextSize, + cost: record.cost, + } + + void (async () => { + await store!.append(usageRecord) + + const result = budget.check() + if (result.message) { + const notifications = ctx.getService('notifications') + if (notifications) { + await notifications.notifyAll({ + sessionId: record.sessionId, + type: 'budget_warning', + summary: result.message, + }) + } + } + })() + }) as (...args: unknown[]) => void) + + // Register /usage command + ctx.registerCommand({ + name: 'usage', + description: 'Show usage summary for current month', + category: 'plugin', + handler: async () => { + const status = budget.getStatus() + const lines = [ + 'Usage (this month):', + ` Spent: $${status.used.toFixed(2)}`, + ` Budget: ${status.budget > 0 ? `$${status.budget.toFixed(2)}` : 'not set'}`, + ` Status: ${status.status} (${status.percent}%)`, + ] + return { type: 'text' as const, text: lines.join('\n') } + }, + }) + + // Expose service for other plugins + ctx.registerService('usage', { store, budget }) + + ctx.log.info('Usage tracking ready') + }, + + async teardown() { + if (store) { + await store.flush() + store.destroy() + } + }, + + async install(ctx: InstallContext) { + const budget = await ctx.terminal.text({ + message: 'Monthly budget in USD (0 = no limit):', + defaultValue: '0', + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 0) return 'Must be a non-negative number' + return undefined + }, + }) + + const threshold = await ctx.terminal.text({ + message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):', + defaultValue: '0.8', + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1' + return undefined + }, + }) + + const retention = await ctx.terminal.text({ + message: 'Retention days:', + defaultValue: '90', + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 1) return 'Must be a positive number' + return undefined + }, + }) + + await ctx.settings.setAll({ + monthlyBudget: Number(budget.trim()), + warningThreshold: Number(threshold.trim()), + retentionDays: Number(retention.trim()), + }) + + ctx.terminal.log.success('Usage plugin configured') + }, + + async configure(ctx: InstallContext) { + const current = await ctx.settings.getAll() + + const budget = await ctx.terminal.text({ + message: 'Monthly budget in USD (0 = no limit):', + defaultValue: String(current.monthlyBudget ?? 0), + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 0) return 'Must be a non-negative number' + return undefined + }, + }) + + const threshold = await ctx.terminal.text({ + message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):', + defaultValue: String(current.warningThreshold ?? 0.8), + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1' + return undefined + }, + }) + + const retention = await ctx.terminal.text({ + message: 'Retention days:', + defaultValue: String(current.retentionDays ?? 90), + validate: (v) => { + const n = Number(v.trim()) + if (isNaN(n) || n < 1) return 'Must be a positive number' + return undefined + }, + }) + + await ctx.settings.setAll({ + monthlyBudget: Number(budget.trim()), + warningThreshold: Number(threshold.trim()), + retentionDays: Number(retention.trim()), + }) + + ctx.terminal.log.success('Usage plugin configured') + }, + + async uninstall(ctx: InstallContext, opts: { purge: boolean }) { + if (opts.purge) { + await ctx.settings.clear() + } + ctx.terminal.log.success('Usage plugin removed') + }, + } +} + +export default createUsagePlugin() diff --git a/src/plugins/usage/usage-budget.ts b/src/plugins/usage/usage-budget.ts new file mode 100644 index 0000000..940c573 --- /dev/null +++ b/src/plugins/usage/usage-budget.ts @@ -0,0 +1,72 @@ +import type { UsageStore } from './usage-store.js' + +export interface UsagePluginConfig { + monthlyBudget?: number + warningThreshold?: number + retentionDays?: number +} + +export type BudgetStatus = 'ok' | 'warning' | 'exceeded' + +export class UsageBudget { + private lastNotifiedStatus: BudgetStatus = 'ok' + private lastNotifiedMonth: number + + constructor( + private store: UsageStore, + private config: UsagePluginConfig, + ) { + this.lastNotifiedMonth = new Date().getMonth() + } + + /** Check budget and return notification if status changed */ + check(): { status: BudgetStatus; message?: string } { + const budget = this.config.monthlyBudget ?? 0 + if (budget <= 0) return { status: 'ok' } + + const { totalCost } = this.store.getMonthlyTotal() + const percent = totalCost / budget + const threshold = this.config.warningThreshold ?? 0.8 + const currentMonth = new Date().getMonth() + + // Reset notification tracking on month change + if (currentMonth !== this.lastNotifiedMonth) { + this.lastNotifiedStatus = 'ok' + this.lastNotifiedMonth = currentMonth + } + + let status: BudgetStatus = 'ok' + if (percent >= 1) status = 'exceeded' + else if (percent >= threshold) status = 'warning' + + // Only notify on status escalation (ok -> warning -> exceeded) + let message: string | undefined + if (status !== 'ok' && status !== this.lastNotifiedStatus) { + const bar = this.progressBar(percent) + message = status === 'exceeded' + ? `Budget exceeded! ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)}` + : `Budget warning: ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)} (${(percent * 100).toFixed(0)}%)` + this.lastNotifiedStatus = status + } + + return { status, message } + } + + /** Get current budget status for /usage command */ + getStatus(): { status: string; used: number; budget: number; percent: number } { + const { totalCost } = this.store.getMonthlyTotal() + const budget = this.config.monthlyBudget ?? 0 + const percent = budget > 0 ? Math.round((totalCost / budget) * 100) : 0 + let status = 'ok' + if (budget > 0) { + if (totalCost >= budget) status = 'exceeded' + else if (totalCost >= budget * (this.config.warningThreshold ?? 0.8)) status = 'warning' + } + return { status, used: totalCost, budget, percent } + } + + progressBar(percent: number): string { + const filled = Math.min(Math.round(percent * 10), 10) + return '\u2588'.repeat(filled) + '\u2591'.repeat(10 - filled) + } +} diff --git a/src/plugins/usage/usage-store.ts b/src/plugins/usage/usage-store.ts new file mode 100644 index 0000000..ffd3548 --- /dev/null +++ b/src/plugins/usage/usage-store.ts @@ -0,0 +1,89 @@ +import type { PluginStorage } from '../../core/plugin/types.js' +import type { UsageRecord } from '../../core/types.js' + +const DEBOUNCE_MS = 2000 + +export class UsageStore { + private cache = new Map() + private dirty = new Set() + private flushTimer: ReturnType | null = null + + constructor(private storage: PluginStorage) {} + + /** Load current month's records into memory on startup */ + async loadFromStorage(): Promise { + const key = this.monthKey(new Date().toISOString()) + const records = (await this.storage.get(key)) ?? [] + this.cache.set(key, records) + } + + /** Append a record (in-memory, schedules debounced flush) */ + async append(record: UsageRecord): Promise { + const key = this.monthKey(record.timestamp) + if (!this.cache.has(key)) { + const existing = (await this.storage.get(key)) ?? [] + this.cache.set(key, existing) + } + this.cache.get(key)!.push(record) + this.dirty.add(key) + this.scheduleFlush() + } + + /** Get monthly cost total (reads from cache) */ + getMonthlyTotal(date?: Date): { totalCost: number; currency: string } { + const key = this.monthKey((date ?? new Date()).toISOString()) + const records = this.cache.get(key) ?? [] + const totalCost = records.reduce((sum, r) => sum + (r.cost?.amount ?? 0), 0) + const currency = records.find(r => r.cost?.currency)?.cost?.currency ?? 'USD' + return { totalCost, currency } + } + + /** Flush all dirty keys to storage immediately */ + async flush(): Promise { + if (this.flushTimer) { + clearTimeout(this.flushTimer) + this.flushTimer = null + } + for (const key of this.dirty) { + const records = this.cache.get(key) + if (records) await this.storage.set(key, records) + } + this.dirty.clear() + } + + /** Delete records older than retention period */ + async cleanupExpired(retentionDays: number): Promise { + const keys = await this.storage.list() + const cutoff = new Date() + cutoff.setDate(cutoff.getDate() - retentionDays) + const cutoffKey = this.monthKey(cutoff.toISOString()) + + for (const key of keys) { + if (key.startsWith('records:') && key < cutoffKey) { + await this.storage.delete(key) + this.cache.delete(key) + } + } + } + + /** Destroy timers for clean shutdown */ + destroy(): void { + if (this.flushTimer) { + clearTimeout(this.flushTimer) + this.flushTimer = null + } + } + + private scheduleFlush(): void { + if (this.flushTimer) return + this.flushTimer = setTimeout(() => { + this.flushTimer = null + void this.flush() + }, DEBOUNCE_MS) + } + + private monthKey(timestamp: string): string { + const d = new Date(timestamp) + return `records:${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}` + } +} From 89878220328ad1b252c9a0f5b3ea9dc3f4b2accc Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:28:52 +0700 Subject: [PATCH 5/7] docs: update review findings with fix status --- ...26-03-28-codebase-logic-review-findings.md | 64 ++++++------------- 1 file changed, 21 insertions(+), 43 deletions(-) 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 index d3e52ce..4868870 100644 --- a/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md +++ b/docs/superpowers/specs/2026-03-28-codebase-logic-review-findings.md @@ -266,51 +266,29 @@ These issues involve complex interactions between multiple services where timing --- -# 5. Summary & Priority +# 5. Fix Status -## Fix Priority +## Completed (4 commits on fix/codebase-logic-review) -### Batch 1 — Quick code fixes (1-5 lines each) -1. **C1** — Guard processPrompt for finished state -2. **C2** — Add cancelled to error transitions -3. **C5** — Remove thinking indicator on timeout -4. **F9** — Move voiceMode "next" reset after successful prompt -5. **C8** — Unref permission gate timer -6. **C13** — Wrap abortPrompt in try-catch in cancelSession (agent may be dead) -7. **C16** — Remove draft from map after finalize in shared DraftManager +| 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 | -### Batch 2 — Session lifecycle fixes -8. **C12** — Set session.threadId BEFORE createSession in lazy resume (events dropped during spawn) -9. **F1+F2** — Fix lazy resume: skip cancelled, fallback to fresh on failure -10. **C15** — Backup corrupt sessions.json as .bak before starting empty +**Total fixed: 30 items** (all code bugs + most feature issues) +**Tests: 134 files, 1746 tests passing** -### Batch 3 — API/CLI field mismatches -11. **F19** — Fix CLI api session field access (.session wrapper + field names) -12. **F20** — Fix CLI api health field access (uptime, memory) -13. **F21** — Use AgentCatalog.resolve() in API sessions route +## Remaining (deferred) -### Batch 4 — Broken features -14. **F3+F4** — Rewrite /archive: keep agent alive + recreate topic -15. **F11+F12** — Fix /tts to set voiceMode + read config -16. **F18** — Create usage plugin (UsageStore + UsageBudget + /usage command) -17. **F13** — ThinkingIndicator dismiss() should delete message -18. **C17** — ThinkingIndicator: delete message if dismissed during queue wait - -### Batch 5 — Error handling & stability -19. **C3** — Validate config before writing to disk -20. **C4** — Close session logger file descriptors -21. **C6** — Clean up spinner/logger on boot failure -22. **C9** — Catch sendMessage middleware errors -23. **C14** — ToolCardState appendUsage: use scheduleFlush instead of immediate flush - -### Batch 6 — Missing features -24. **F10** — Implement tts_strip event -25. **F7** — Over-budget interactive selection for /resume -26. **F22** — Settings validation at boot -27. **F24** — Telegram /tunnel create/stop commands - -### Batch 6 — Test coverage -22. **T1** — Lazy resume tests -23. **T3** — API route handler tests -24. **T5** — Tunnel tests -25. **T6** — Telegram command handler tests +| # | 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 | From c60a320c18bf1af76d472cb1739e9da181114466 Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:38:08 +0700 Subject: [PATCH 6/7] fix: address code review feedback - Remove redundant threadId assignment in lazy resume (already set via createSession param) - Wrap patchRecord in archive with try-catch (topic already recreated, store update is best-effort) - Add edge case comment in stripPattern for slow TTS synthesis --- src/core/core.ts | 19 +++++++++++-------- src/plugins/telegram/draft-manager.ts | 2 ++ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/core/core.ts b/src/core/core.ts index b49a4b5..d1e2e90 100644 --- a/src/core/core.ts +++ b/src/core/core.ts @@ -206,14 +206,18 @@ export class OpenACPCore { // Rewire session to new topic session.threadId = newThreadId; - // Update session store with new topic ID - const platform: Record = {}; - if (session.channelId === "telegram") { - platform.topicId = Number(newThreadId); - } else { - platform.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"); } - await this.sessionManager.patchRecord(sessionId, { platform }); return { ok: true, newThreadId }; } catch (err) { @@ -653,7 +657,6 @@ export class OpenACPCore { initialName: record.name, threadId: message.threadId, }); - session.threadId = message.threadId; session.activate(); session.dangerousMode = record.dangerousMode ?? false; diff --git a/src/plugins/telegram/draft-manager.ts b/src/plugins/telegram/draft-manager.ts index eb41297..6165428 100644 --- a/src/plugins/telegram/draft-manager.ts +++ b/src/plugins/telegram/draft-manager.ts @@ -113,6 +113,8 @@ export class DraftManager { 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 { From 08bbc6b134e6b4cd829e2d32ead671f7a8049b21 Mon Sep 17 00:00:00 2001 From: 0xmrpeter <0xmrpeter@gmail.com> Date: Sat, 28 Mar 2026 01:39:24 +0700 Subject: [PATCH 7/7] revert: remove usage plugin (extracted to external package) --- src/plugins/core-plugins.ts | 2 - .../usage/__tests__/usage-budget.test.ts | 208 ------------------ .../usage/__tests__/usage-store.test.ts | 198 ----------------- src/plugins/usage/index.ts | 193 ---------------- src/plugins/usage/usage-budget.ts | 72 ------ src/plugins/usage/usage-store.ts | 89 -------- 6 files changed, 762 deletions(-) delete mode 100644 src/plugins/usage/__tests__/usage-budget.test.ts delete mode 100644 src/plugins/usage/__tests__/usage-store.test.ts delete mode 100644 src/plugins/usage/index.ts delete mode 100644 src/plugins/usage/usage-budget.ts delete mode 100644 src/plugins/usage/usage-store.ts diff --git a/src/plugins/core-plugins.ts b/src/plugins/core-plugins.ts index d81eabf..a05682f 100644 --- a/src/plugins/core-plugins.ts +++ b/src/plugins/core-plugins.ts @@ -8,7 +8,6 @@ import fileServicePlugin from './file-service/index.js' import contextPlugin from './context/index.js' import speechPlugin from './speech/index.js' import notificationsPlugin from './notifications/index.js' -import usagePlugin from './usage/index.js' import tunnelPlugin from './tunnel/index.js' import apiServerPlugin from './api-server/index.js' import telegramPlugin from './telegram/index.js' @@ -20,7 +19,6 @@ export const corePlugins = [ contextPlugin, speechPlugin, notificationsPlugin, - usagePlugin, // Infrastructure plugins tunnelPlugin, apiServerPlugin, diff --git a/src/plugins/usage/__tests__/usage-budget.test.ts b/src/plugins/usage/__tests__/usage-budget.test.ts deleted file mode 100644 index b43ac64..0000000 --- a/src/plugins/usage/__tests__/usage-budget.test.ts +++ /dev/null @@ -1,208 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { UsageBudget } from '../usage-budget.js' -import type { UsagePluginConfig } from '../usage-budget.js' -import { UsageStore } from '../usage-store.js' -import type { PluginStorage } from '../../../core/plugin/types.js' - -function mockStorage(): PluginStorage { - const data = new Map() - return { - get: vi.fn(async (key: string) => data.get(key) as T | undefined), - set: vi.fn(async (key: string, value: T) => { data.set(key, value) }), - delete: vi.fn(async (key: string) => { data.delete(key) }), - list: vi.fn(async () => [...data.keys()]), - getDataDir: vi.fn(() => '/tmp/usage-test'), - } -} - -function makeRecord(cost: number) { - return { - id: `rec-${Math.random()}`, - sessionId: 'sess-1', - agentName: 'claude', - tokensUsed: 1000, - contextSize: 5000, - cost: { amount: cost, currency: 'USD' }, - timestamp: new Date().toISOString(), - } -} - -describe('UsageBudget', () => { - let store: UsageStore - let storage: PluginStorage - - beforeEach(() => { - vi.useFakeTimers() - storage = mockStorage() - store = new UsageStore(storage) - }) - - afterEach(() => { - store.destroy() - vi.useRealTimers() - }) - - describe('check', () => { - it('returns ok when no budget is set', async () => { - const budget = new UsageBudget(store, { monthlyBudget: 0 }) - const result = budget.check() - expect(result.status).toBe('ok') - expect(result.message).toBeUndefined() - }) - - it('returns ok when spending is below threshold', async () => { - await store.append(makeRecord(5.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) - - const result = budget.check() - expect(result.status).toBe('ok') - expect(result.message).toBeUndefined() - }) - - it('returns warning when threshold is crossed', async () => { - await store.append(makeRecord(85.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) - - const result = budget.check() - expect(result.status).toBe('warning') - expect(result.message).toContain('Budget warning') - expect(result.message).toContain('$85.00') - expect(result.message).toContain('$100.00') - expect(result.message).toContain('85%') - }) - - it('returns exceeded when budget is exceeded', async () => { - await store.append(makeRecord(110.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) - - const result = budget.check() - expect(result.status).toBe('exceeded') - expect(result.message).toContain('Budget exceeded') - expect(result.message).toContain('$110.00') - }) - - it('deduplicates notifications - only notifies on status change', async () => { - const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } - - await store.append(makeRecord(85.00)) - const budget = new UsageBudget(store, config) - - // First check: warning with message - const first = budget.check() - expect(first.status).toBe('warning') - expect(first.message).toBeDefined() - - // Second check at same level: no message - const second = budget.check() - expect(second.status).toBe('warning') - expect(second.message).toBeUndefined() - }) - - it('escalates from warning to exceeded', async () => { - const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } - - await store.append(makeRecord(85.00)) - const budget = new UsageBudget(store, config) - - const warning = budget.check() - expect(warning.status).toBe('warning') - expect(warning.message).toBeDefined() - - // Add more cost to exceed budget - await store.append(makeRecord(20.00)) - - const exceeded = budget.check() - expect(exceeded.status).toBe('exceeded') - expect(exceeded.message).toContain('Budget exceeded') - }) - - it('resets notification tracking on month boundary', async () => { - const config: UsagePluginConfig = { monthlyBudget: 100, warningThreshold: 0.8 } - - await store.append(makeRecord(85.00)) - const budget = new UsageBudget(store, config) - - // Trigger warning - const first = budget.check() - expect(first.message).toBeDefined() - - // Simulate month change by advancing time - const nextMonth = new Date() - nextMonth.setMonth(nextMonth.getMonth() + 1) - vi.setSystemTime(nextMonth) - - // Add usage in new month - await store.append(makeRecord(85.00)) - - // Should get a new warning since month changed - const afterReset = budget.check() - expect(afterReset.status).toBe('warning') - expect(afterReset.message).toBeDefined() - }) - }) - - describe('getStatus', () => { - it('returns status with zero budget', () => { - const budget = new UsageBudget(store, { monthlyBudget: 0 }) - const status = budget.getStatus() - expect(status.status).toBe('ok') - expect(status.used).toBe(0) - expect(status.budget).toBe(0) - expect(status.percent).toBe(0) - }) - - it('returns correct percentage', async () => { - await store.append(makeRecord(25.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - - const status = budget.getStatus() - expect(status.status).toBe('ok') - expect(status.used).toBeCloseTo(25.00) - expect(status.budget).toBe(100) - expect(status.percent).toBe(25) - }) - - it('returns warning status at threshold', async () => { - await store.append(makeRecord(80.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100, warningThreshold: 0.8 }) - - const status = budget.getStatus() - expect(status.status).toBe('warning') - }) - - it('returns exceeded status over budget', async () => { - await store.append(makeRecord(120.00)) - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - - const status = budget.getStatus() - expect(status.status).toBe('exceeded') - expect(status.percent).toBe(120) - }) - }) - - describe('progressBar', () => { - it('renders correct bar at 50%', () => { - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - const bar = budget.progressBar(0.5) - expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2591\u2591\u2591\u2591\u2591') - }) - - it('renders full bar at 100%', () => { - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - const bar = budget.progressBar(1.0) - expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') - }) - - it('caps bar at 10 filled blocks for values over 100%', () => { - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - const bar = budget.progressBar(1.5) - expect(bar).toBe('\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588') - }) - - it('renders empty bar at 0%', () => { - const budget = new UsageBudget(store, { monthlyBudget: 100 }) - const bar = budget.progressBar(0) - expect(bar).toBe('\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591\u2591') - }) - }) -}) diff --git a/src/plugins/usage/__tests__/usage-store.test.ts b/src/plugins/usage/__tests__/usage-store.test.ts deleted file mode 100644 index b4e67e3..0000000 --- a/src/plugins/usage/__tests__/usage-store.test.ts +++ /dev/null @@ -1,198 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { UsageStore } from '../usage-store.js' -import type { PluginStorage } from '../../../core/plugin/types.js' -import type { UsageRecord } from '../../../core/types.js' - -function mockStorage(): PluginStorage { - const data = new Map() - return { - get: vi.fn(async (key: string) => data.get(key) as T | undefined), - set: vi.fn(async (key: string, value: T) => { data.set(key, value) }), - delete: vi.fn(async (key: string) => { data.delete(key) }), - list: vi.fn(async () => [...data.keys()]), - getDataDir: vi.fn(() => '/tmp/usage-test'), - } -} - -function makeRecord(overrides: Partial = {}): UsageRecord { - return { - id: 'rec-1', - sessionId: 'sess-1', - agentName: 'claude', - tokensUsed: 1000, - contextSize: 5000, - cost: { amount: 0.05, currency: 'USD' }, - timestamp: new Date().toISOString(), - ...overrides, - } -} - -describe('UsageStore', () => { - let storage: PluginStorage - let store: UsageStore - - beforeEach(() => { - vi.useFakeTimers() - storage = mockStorage() - store = new UsageStore(storage) - }) - - afterEach(() => { - store.destroy() - vi.useRealTimers() - }) - - describe('append', () => { - it('adds record to in-memory cache', async () => { - const record = makeRecord() - await store.append(record) - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBe(0.05) - expect(total.currency).toBe('USD') - }) - - it('loads from storage on first append for a new month key', async () => { - const existing = makeRecord({ id: 'old-1', cost: { amount: 0.10, currency: 'USD' } }) - const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` - await storage.set(key, [existing]) - - await store.append(makeRecord({ id: 'new-1' })) - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBeCloseTo(0.15) - }) - - it('schedules debounced flush', async () => { - await store.append(makeRecord()) - expect(storage.set).not.toHaveBeenCalledWith(expect.stringContaining('records:'), expect.anything()) - - vi.advanceTimersByTime(2000) - await vi.waitFor(() => { - expect(storage.set).toHaveBeenCalled() - }) - }) - }) - - describe('getMonthlyTotal', () => { - it('returns zero for empty cache', () => { - const total = store.getMonthlyTotal() - expect(total.totalCost).toBe(0) - expect(total.currency).toBe('USD') - }) - - it('sums costs across multiple records', async () => { - await store.append(makeRecord({ id: '1', cost: { amount: 0.10, currency: 'USD' } })) - await store.append(makeRecord({ id: '2', cost: { amount: 0.25, currency: 'USD' } })) - await store.append(makeRecord({ id: '3', cost: { amount: 0.05, currency: 'USD' } })) - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBeCloseTo(0.40) - }) - - it('handles records without cost', async () => { - await store.append(makeRecord({ id: '1', cost: undefined })) - await store.append(makeRecord({ id: '2', cost: { amount: 0.10, currency: 'USD' } })) - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBeCloseTo(0.10) - }) - - it('returns totals for specific month', async () => { - await store.append(makeRecord({ id: '1', timestamp: '2026-01-15T00:00:00Z', cost: { amount: 0.50, currency: 'USD' } })) - await store.append(makeRecord({ id: '2', timestamp: '2026-02-15T00:00:00Z', cost: { amount: 0.30, currency: 'USD' } })) - - const janTotal = store.getMonthlyTotal(new Date('2026-01-15')) - expect(janTotal.totalCost).toBeCloseTo(0.50) - - const febTotal = store.getMonthlyTotal(new Date('2026-02-15')) - expect(febTotal.totalCost).toBeCloseTo(0.30) - }) - }) - - describe('flush', () => { - it('writes all dirty keys to storage', async () => { - await store.append(makeRecord()) - await store.flush() - - const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` - expect(storage.set).toHaveBeenCalledWith(key, expect.any(Array)) - }) - - it('clears dirty set after flush', async () => { - await store.append(makeRecord()); - - // Reset mock to track only flush calls - (storage.set as ReturnType).mockClear() - - await store.flush() - expect(storage.set).toHaveBeenCalledTimes(1); - - // Second flush should not write again - (storage.set as ReturnType).mockClear() - await store.flush() - expect(storage.set).not.toHaveBeenCalled() - }) - - it('cancels pending debounced flush', async () => { - await store.append(makeRecord()) - - // Manually flush — this should clear the pending debounce timer - // and write all dirty keys to storage - store.flush() - - // Advance past the debounce period and verify no extra writes occur - const setCalls = (storage.set as ReturnType).mock.calls.length - vi.advanceTimersByTime(5000) - - // No additional set calls beyond what flush() already did - expect((storage.set as ReturnType).mock.calls.length).toBe(setCalls) - }) - }) - - describe('loadFromStorage', () => { - it('loads current month records into cache', async () => { - const key = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` - const existing = [makeRecord({ id: 'stored-1', cost: { amount: 1.00, currency: 'USD' } })] - await storage.set(key, existing) - - await store.loadFromStorage() - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBeCloseTo(1.00) - }) - - it('handles empty storage gracefully', async () => { - await store.loadFromStorage() - - const total = store.getMonthlyTotal() - expect(total.totalCost).toBe(0) - }) - }) - - describe('cleanupExpired', () => { - it('deletes records older than retention period', async () => { - // Store old records under a key from 6 months ago - await storage.set('records:2025-01', [makeRecord()]) - await storage.set('records:2025-06', [makeRecord()]) - // Current month should stay - const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` - await storage.set(currentKey, [makeRecord()]) - - await store.cleanupExpired(90) - - expect(storage.delete).toHaveBeenCalledWith('records:2025-01') - expect(storage.delete).toHaveBeenCalledWith('records:2025-06') - expect(storage.delete).not.toHaveBeenCalledWith(currentKey) - }) - - it('does nothing when no expired keys exist', async () => { - const currentKey = `records:${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}` - await storage.set(currentKey, [makeRecord()]) - - await store.cleanupExpired(90) - - expect(storage.delete).not.toHaveBeenCalled() - }) - }) -}) diff --git a/src/plugins/usage/index.ts b/src/plugins/usage/index.ts deleted file mode 100644 index 88288aa..0000000 --- a/src/plugins/usage/index.ts +++ /dev/null @@ -1,193 +0,0 @@ -import { nanoid } from 'nanoid' -import type { OpenACPPlugin, InstallContext, NotificationService } from '../../core/plugin/types.js' -import type { UsageRecordEvent, UsageRecord } from '../../core/types.js' -import { UsageStore } from './usage-store.js' -import { UsageBudget } from './usage-budget.js' -import type { UsagePluginConfig } from './usage-budget.js' - -function createUsagePlugin(): OpenACPPlugin { - let store: UsageStore | undefined - - return { - name: '@openacp/usage', - version: '1.0.0', - description: 'Token usage tracking and budget enforcement', - essential: false, - optionalPluginDependencies: { '@openacp/notifications': '^1.0.0' }, - permissions: [ - 'events:read', - 'services:register', - 'services:use', - 'commands:register', - 'storage:read', - 'storage:write', - ], - - async setup(ctx) { - const config: UsagePluginConfig = { - monthlyBudget: (ctx.pluginConfig.monthlyBudget as number | undefined) ?? 0, - warningThreshold: (ctx.pluginConfig.warningThreshold as number | undefined) ?? 0.8, - retentionDays: (ctx.pluginConfig.retentionDays as number | undefined) ?? 90, - } - - store = new UsageStore(ctx.storage) - const budget = new UsageBudget(store, config) - - // Load existing records into memory cache - await store.loadFromStorage() - - // Clean old records on startup - await store.cleanupExpired(config.retentionDays ?? 90) - - // Listen to usage events from core - ctx.on('usage:recorded', ((...args: unknown[]) => { - const record = args[0] as UsageRecordEvent - const usageRecord: UsageRecord = { - id: nanoid(), - sessionId: record.sessionId, - agentName: record.agentName, - timestamp: record.timestamp, - tokensUsed: record.tokensUsed, - contextSize: record.contextSize, - cost: record.cost, - } - - void (async () => { - await store!.append(usageRecord) - - const result = budget.check() - if (result.message) { - const notifications = ctx.getService('notifications') - if (notifications) { - await notifications.notifyAll({ - sessionId: record.sessionId, - type: 'budget_warning', - summary: result.message, - }) - } - } - })() - }) as (...args: unknown[]) => void) - - // Register /usage command - ctx.registerCommand({ - name: 'usage', - description: 'Show usage summary for current month', - category: 'plugin', - handler: async () => { - const status = budget.getStatus() - const lines = [ - 'Usage (this month):', - ` Spent: $${status.used.toFixed(2)}`, - ` Budget: ${status.budget > 0 ? `$${status.budget.toFixed(2)}` : 'not set'}`, - ` Status: ${status.status} (${status.percent}%)`, - ] - return { type: 'text' as const, text: lines.join('\n') } - }, - }) - - // Expose service for other plugins - ctx.registerService('usage', { store, budget }) - - ctx.log.info('Usage tracking ready') - }, - - async teardown() { - if (store) { - await store.flush() - store.destroy() - } - }, - - async install(ctx: InstallContext) { - const budget = await ctx.terminal.text({ - message: 'Monthly budget in USD (0 = no limit):', - defaultValue: '0', - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 0) return 'Must be a non-negative number' - return undefined - }, - }) - - const threshold = await ctx.terminal.text({ - message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):', - defaultValue: '0.8', - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1' - return undefined - }, - }) - - const retention = await ctx.terminal.text({ - message: 'Retention days:', - defaultValue: '90', - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 1) return 'Must be a positive number' - return undefined - }, - }) - - await ctx.settings.setAll({ - monthlyBudget: Number(budget.trim()), - warningThreshold: Number(threshold.trim()), - retentionDays: Number(retention.trim()), - }) - - ctx.terminal.log.success('Usage plugin configured') - }, - - async configure(ctx: InstallContext) { - const current = await ctx.settings.getAll() - - const budget = await ctx.terminal.text({ - message: 'Monthly budget in USD (0 = no limit):', - defaultValue: String(current.monthlyBudget ?? 0), - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 0) return 'Must be a non-negative number' - return undefined - }, - }) - - const threshold = await ctx.terminal.text({ - message: 'Warning threshold (0-1, e.g. 0.8 = warn at 80%):', - defaultValue: String(current.warningThreshold ?? 0.8), - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 0 || n > 1) return 'Must be between 0 and 1' - return undefined - }, - }) - - const retention = await ctx.terminal.text({ - message: 'Retention days:', - defaultValue: String(current.retentionDays ?? 90), - validate: (v) => { - const n = Number(v.trim()) - if (isNaN(n) || n < 1) return 'Must be a positive number' - return undefined - }, - }) - - await ctx.settings.setAll({ - monthlyBudget: Number(budget.trim()), - warningThreshold: Number(threshold.trim()), - retentionDays: Number(retention.trim()), - }) - - ctx.terminal.log.success('Usage plugin configured') - }, - - async uninstall(ctx: InstallContext, opts: { purge: boolean }) { - if (opts.purge) { - await ctx.settings.clear() - } - ctx.terminal.log.success('Usage plugin removed') - }, - } -} - -export default createUsagePlugin() diff --git a/src/plugins/usage/usage-budget.ts b/src/plugins/usage/usage-budget.ts deleted file mode 100644 index 940c573..0000000 --- a/src/plugins/usage/usage-budget.ts +++ /dev/null @@ -1,72 +0,0 @@ -import type { UsageStore } from './usage-store.js' - -export interface UsagePluginConfig { - monthlyBudget?: number - warningThreshold?: number - retentionDays?: number -} - -export type BudgetStatus = 'ok' | 'warning' | 'exceeded' - -export class UsageBudget { - private lastNotifiedStatus: BudgetStatus = 'ok' - private lastNotifiedMonth: number - - constructor( - private store: UsageStore, - private config: UsagePluginConfig, - ) { - this.lastNotifiedMonth = new Date().getMonth() - } - - /** Check budget and return notification if status changed */ - check(): { status: BudgetStatus; message?: string } { - const budget = this.config.monthlyBudget ?? 0 - if (budget <= 0) return { status: 'ok' } - - const { totalCost } = this.store.getMonthlyTotal() - const percent = totalCost / budget - const threshold = this.config.warningThreshold ?? 0.8 - const currentMonth = new Date().getMonth() - - // Reset notification tracking on month change - if (currentMonth !== this.lastNotifiedMonth) { - this.lastNotifiedStatus = 'ok' - this.lastNotifiedMonth = currentMonth - } - - let status: BudgetStatus = 'ok' - if (percent >= 1) status = 'exceeded' - else if (percent >= threshold) status = 'warning' - - // Only notify on status escalation (ok -> warning -> exceeded) - let message: string | undefined - if (status !== 'ok' && status !== this.lastNotifiedStatus) { - const bar = this.progressBar(percent) - message = status === 'exceeded' - ? `Budget exceeded! ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)}` - : `Budget warning: ${bar} $${totalCost.toFixed(2)} / $${budget.toFixed(2)} (${(percent * 100).toFixed(0)}%)` - this.lastNotifiedStatus = status - } - - return { status, message } - } - - /** Get current budget status for /usage command */ - getStatus(): { status: string; used: number; budget: number; percent: number } { - const { totalCost } = this.store.getMonthlyTotal() - const budget = this.config.monthlyBudget ?? 0 - const percent = budget > 0 ? Math.round((totalCost / budget) * 100) : 0 - let status = 'ok' - if (budget > 0) { - if (totalCost >= budget) status = 'exceeded' - else if (totalCost >= budget * (this.config.warningThreshold ?? 0.8)) status = 'warning' - } - return { status, used: totalCost, budget, percent } - } - - progressBar(percent: number): string { - const filled = Math.min(Math.round(percent * 10), 10) - return '\u2588'.repeat(filled) + '\u2591'.repeat(10 - filled) - } -} diff --git a/src/plugins/usage/usage-store.ts b/src/plugins/usage/usage-store.ts deleted file mode 100644 index ffd3548..0000000 --- a/src/plugins/usage/usage-store.ts +++ /dev/null @@ -1,89 +0,0 @@ -import type { PluginStorage } from '../../core/plugin/types.js' -import type { UsageRecord } from '../../core/types.js' - -const DEBOUNCE_MS = 2000 - -export class UsageStore { - private cache = new Map() - private dirty = new Set() - private flushTimer: ReturnType | null = null - - constructor(private storage: PluginStorage) {} - - /** Load current month's records into memory on startup */ - async loadFromStorage(): Promise { - const key = this.monthKey(new Date().toISOString()) - const records = (await this.storage.get(key)) ?? [] - this.cache.set(key, records) - } - - /** Append a record (in-memory, schedules debounced flush) */ - async append(record: UsageRecord): Promise { - const key = this.monthKey(record.timestamp) - if (!this.cache.has(key)) { - const existing = (await this.storage.get(key)) ?? [] - this.cache.set(key, existing) - } - this.cache.get(key)!.push(record) - this.dirty.add(key) - this.scheduleFlush() - } - - /** Get monthly cost total (reads from cache) */ - getMonthlyTotal(date?: Date): { totalCost: number; currency: string } { - const key = this.monthKey((date ?? new Date()).toISOString()) - const records = this.cache.get(key) ?? [] - const totalCost = records.reduce((sum, r) => sum + (r.cost?.amount ?? 0), 0) - const currency = records.find(r => r.cost?.currency)?.cost?.currency ?? 'USD' - return { totalCost, currency } - } - - /** Flush all dirty keys to storage immediately */ - async flush(): Promise { - if (this.flushTimer) { - clearTimeout(this.flushTimer) - this.flushTimer = null - } - for (const key of this.dirty) { - const records = this.cache.get(key) - if (records) await this.storage.set(key, records) - } - this.dirty.clear() - } - - /** Delete records older than retention period */ - async cleanupExpired(retentionDays: number): Promise { - const keys = await this.storage.list() - const cutoff = new Date() - cutoff.setDate(cutoff.getDate() - retentionDays) - const cutoffKey = this.monthKey(cutoff.toISOString()) - - for (const key of keys) { - if (key.startsWith('records:') && key < cutoffKey) { - await this.storage.delete(key) - this.cache.delete(key) - } - } - } - - /** Destroy timers for clean shutdown */ - destroy(): void { - if (this.flushTimer) { - clearTimeout(this.flushTimer) - this.flushTimer = null - } - } - - private scheduleFlush(): void { - if (this.flushTimer) return - this.flushTimer = setTimeout(() => { - this.flushTimer = null - void this.flush() - }, DEBOUNCE_MS) - } - - private monthKey(timestamp: string): string { - const d = new Date(timestamp) - return `records:${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}` - } -}