|
| 1 | +import fs from "node:fs/promises"; |
| 2 | +import path from "node:path"; |
| 3 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 4 | +import { hasTerminalControl } from "../../../packages/terminal-core/src/safe-text.js"; |
| 5 | +import { createDeferred } from "../../../test/helpers/promise.js"; |
| 6 | +import { createTempDirTracker } from "../../../test/helpers/temp-dir.js"; |
| 7 | +import { createEmptyPluginRegistry } from "../../plugins/registry-empty.js"; |
| 8 | +import { withPluginRuntimeRegistryScope } from "../../plugins/runtime/gateway-request-scope.js"; |
| 9 | +import { |
| 10 | + closeOpenClawStateDatabaseByPath, |
| 11 | + closeOpenClawStateDatabaseForTest, |
| 12 | + getOpenClawStateDatabaseIfOpen, |
| 13 | +} from "../../state/openclaw-state-db.js"; |
| 14 | +import type { |
| 15 | + TranscriptSourceProvider, |
| 16 | + TranscriptStartRequest, |
| 17 | + TranscriptStopRequest, |
| 18 | +} from "../../transcripts/provider-types.js"; |
| 19 | +import { TranscriptsStore } from "../../transcripts/store.js"; |
| 20 | +import { createTranscriptsAutoStartService, createTranscriptsTool } from "./transcripts-tool.js"; |
| 21 | + |
| 22 | +const tempDirs = createTempDirTracker(); |
| 23 | +const capturedText = "Private captured decision: keep these notes out of operator logs."; |
| 24 | +const obstruction = "existing file; do not overwrite\n"; |
| 25 | +const credential = "fixture-secret-value-1234567890"; |
| 26 | +const providerError = `fixture stop failure\n\u001b[31mred\u001b[0m\u0085 token=${credential} ${"🦞".repeat(2_000)}`; |
| 27 | + |
| 28 | +afterEach(() => { |
| 29 | + closeOpenClawStateDatabaseForTest(); |
| 30 | + tempDirs.cleanup(); |
| 31 | +}); |
| 32 | + |
| 33 | +describe("transcripts auto-start stop reporting", () => { |
| 34 | + it.each([ |
| 35 | + { name: "export failure", blocked: true, outcome: "ok", manual: false }, |
| 36 | + { name: "fulfilled provider warning", blocked: false, outcome: "warn", manual: false }, |
| 37 | + { name: "both warnings", blocked: true, outcome: "warn", manual: false }, |
| 38 | + { name: "healthy stop", blocked: false, outcome: "ok", manual: false }, |
| 39 | + { name: "thrown provider error", blocked: false, outcome: "throw", manual: false }, |
| 40 | + { |
| 41 | + name: "manual export failure then skipped auto-stop", |
| 42 | + blocked: true, |
| 43 | + outcome: "ok", |
| 44 | + manual: true, |
| 45 | + }, |
| 46 | + { |
| 47 | + name: "manual both warnings then skipped auto-stop", |
| 48 | + blocked: true, |
| 49 | + outcome: "warn", |
| 50 | + manual: true, |
| 51 | + }, |
| 52 | + ])("$name preserves state and finishes siblings", async ({ blocked, outcome, manual }) => { |
| 53 | + const stateDir = await fs.realpath(tempDirs.make("openclaw-transcripts-auto-stop-")); |
| 54 | + const options = { env: { ...process.env, OPENCLAW_STATE_DIR: stateDir } }; |
| 55 | + const exportRoot = path.join(stateDir, "transcripts"); |
| 56 | + const store = new TranscriptsStore(exportRoot, options); |
| 57 | + const requests = new Map<string, TranscriptStartRequest>(); |
| 58 | + const subjectId = "subject"; |
| 59 | + const ids = [subjectId, "healthy-sibling"]; |
| 60 | + const gates = new Map(ids.map((id) => [id, createDeferred()])); |
| 61 | + const stop = vi.fn(async ({ sessionId }: TranscriptStopRequest) => { |
| 62 | + if (sessionId === subjectId) { |
| 63 | + if (outcome === "throw" && stop.mock.calls.length === 1) { |
| 64 | + throw new Error(providerError); |
| 65 | + } |
| 66 | + if (outcome === "warn") { |
| 67 | + return { ok: false as const, error: providerError }; |
| 68 | + } |
| 69 | + } |
| 70 | + return { ok: true as const, sessionId }; |
| 71 | + }); |
| 72 | + const provider: TranscriptSourceProvider = { |
| 73 | + id: "stop-reporting-fixture", |
| 74 | + name: "Stop reporting fixture", |
| 75 | + sourceKinds: ["live-caption"], |
| 76 | + async start(request) { |
| 77 | + requests.set(request.session.sessionId, request); |
| 78 | + await gates.get(request.session.sessionId)?.promise; |
| 79 | + return { ok: true, session: request.session }; |
| 80 | + }, |
| 81 | + stop, |
| 82 | + }; |
| 83 | + const registry = createEmptyPluginRegistry(); |
| 84 | + registry.transcriptSourceProviders.push({ |
| 85 | + pluginId: provider.id, |
| 86 | + provider, |
| 87 | + source: import.meta.url, |
| 88 | + }); |
| 89 | + const logger = { warn: vi.fn<(message: string) => void>() }; |
| 90 | + const ctx = { |
| 91 | + config: { |
| 92 | + transcripts: { |
| 93 | + enabled: true, |
| 94 | + autoStart: ids.map((sessionId) => ({ providerId: provider.id, sessionId })), |
| 95 | + }, |
| 96 | + }, |
| 97 | + stateDir, |
| 98 | + logger, |
| 99 | + caller: { kind: "operator" as const, source: "local" as const }, |
| 100 | + }; |
| 101 | + const service = createTranscriptsAutoStartService(ctx); |
| 102 | + const tool = createTranscriptsTool(ctx); |
| 103 | + const execute = (action: string, sessionId?: string) => |
| 104 | + tool.execute("stop-proof", { action, sessionId }); |
| 105 | + |
| 106 | + await withPluginRuntimeRegistryScope(registry, async () => { |
| 107 | + try { |
| 108 | + service.start(); |
| 109 | + for (const id of ids) { |
| 110 | + gates.get(id)?.resolve(); |
| 111 | + await vi.waitFor(async () => { |
| 112 | + expect(await execute("status")).toMatchObject({ |
| 113 | + details: { |
| 114 | + active: expect.arrayContaining([expect.objectContaining({ sessionId: id })]), |
| 115 | + }, |
| 116 | + }); |
| 117 | + }); |
| 118 | + const request = requests.get(id)!; |
| 119 | + await request.onUtterance({ text: capturedText, final: true }); |
| 120 | + await expect(store.readUtterancesForSession(request.session)).resolves.toEqual([ |
| 121 | + expect.objectContaining({ text: capturedText }), |
| 122 | + ]); |
| 123 | + } |
| 124 | + const subject = requests.get(subjectId)!.session; |
| 125 | + const sessionDir = store.sessionDir(subject); |
| 126 | + const summaryPath = path.join(sessionDir, "summary.md"); |
| 127 | + if (blocked) { |
| 128 | + // Fault only the optional export, after provider admission and durable capture. |
| 129 | + await fs.mkdir(path.dirname(sessionDir), { recursive: true }); |
| 130 | + await fs.writeFile(sessionDir, obstruction, { flag: "wx" }); |
| 131 | + } |
| 132 | + if (manual) { |
| 133 | + const result = await execute("stop", subject.sessionId); |
| 134 | + expect(result.details).toMatchObject({ |
| 135 | + summaryExportError: expect.stringContaining("ENOTDIR"), |
| 136 | + intendedSummaryPath: summaryPath, |
| 137 | + summary: { utteranceCount: 1 }, |
| 138 | + }); |
| 139 | + expect(result.details).not.toHaveProperty("summaryPath"); |
| 140 | + if (outcome === "warn") { |
| 141 | + expect(result.details).toHaveProperty("providerStopError", providerError); |
| 142 | + } else { |
| 143 | + expect(result.details).not.toHaveProperty("providerStopError"); |
| 144 | + } |
| 145 | + } |
| 146 | + await expect(service.stop()).resolves.toBeUndefined(); |
| 147 | + expect(stop.mock.calls.map(([request]) => request.sessionId)).toEqual(ids); |
| 148 | + const warnings = logger.warn.mock.calls.map(([message]) => message); |
| 149 | + await service.stop(); |
| 150 | + expect(stop).toHaveBeenCalledTimes(2); |
| 151 | + expect(logger.warn.mock.calls.map(([message]) => message)).toEqual(warnings); |
| 152 | + |
| 153 | + const database = getOpenClawStateDatabaseIfOpen(options)!; |
| 154 | + expect(database.db.isOpen).toBe(true); |
| 155 | + expect(closeOpenClawStateDatabaseByPath(database.path)).toBe(true); |
| 156 | + expect(database.db.isOpen).toBe(false); |
| 157 | + const reopened = new TranscriptsStore(exportRoot, options); |
| 158 | + for (const id of ids) { |
| 159 | + const stored = (await reopened.readSession(id))!; |
| 160 | + const summary = await reopened.readSummary(stored); |
| 161 | + if (id === subject.sessionId && outcome === "throw") { |
| 162 | + expect(stored.stoppedAt).toBeUndefined(); |
| 163 | + expect(summary).toEqual({}); |
| 164 | + continue; |
| 165 | + } |
| 166 | + expect(stored.stoppedAt).toEqual(expect.any(String)); |
| 167 | + expect(summary).toMatchObject({ |
| 168 | + summary: { utteranceCount: 1, transcript: [capturedText] }, |
| 169 | + markdown: expect.stringContaining(capturedText), |
| 170 | + }); |
| 171 | + if (id === subject.sessionId && blocked) { |
| 172 | + expect((await fs.lstat(sessionDir)).isFile()).toBe(true); |
| 173 | + expect(await fs.readFile(sessionDir, "utf8")).toBe(obstruction); |
| 174 | + await expect(fs.readFile(summaryPath)).rejects.toMatchObject({ code: "ENOTDIR" }); |
| 175 | + } else { |
| 176 | + expect( |
| 177 | + await fs.readFile(path.join(reopened.sessionDir(stored), "summary.md"), "utf8"), |
| 178 | + ).toContain(capturedText); |
| 179 | + } |
| 180 | + } |
| 181 | + expect(getOpenClawStateDatabaseIfOpen(options)).not.toBe(database); |
| 182 | + await expect(execute("status")).resolves.toMatchObject({ |
| 183 | + details: { |
| 184 | + active: |
| 185 | + outcome === "throw" |
| 186 | + ? [expect.objectContaining({ sessionId: subject.sessionId })] |
| 187 | + : [], |
| 188 | + }, |
| 189 | + }); |
| 190 | + |
| 191 | + if (manual || (!blocked && outcome === "ok")) { |
| 192 | + expect(warnings).toEqual([]); |
| 193 | + } else { |
| 194 | + expect(warnings.length).toBeGreaterThan(0); |
| 195 | + const logged = warnings.join(" "); |
| 196 | + expect(logged).toContain(subject.sessionId); |
| 197 | + if (blocked) { |
| 198 | + expect(logged).toMatch(/summary saved.*export failed/i); |
| 199 | + expect(logged).toContain("ENOTDIR"); |
| 200 | + expect(logged).toContain(JSON.stringify(summaryPath)); |
| 201 | + expect(logged).toContain("openclaw transcripts path <session>"); |
| 202 | + expect(logged).toMatch(/(?:repair|correct).*destination/i); |
| 203 | + } |
| 204 | + if (outcome !== "ok") { |
| 205 | + expect(logged).toContain("fixture stop failure"); |
| 206 | + expect(logged).toMatch(outcome === "throw" ? /stop failed/ : /provider stop failed/); |
| 207 | + } |
| 208 | + for (const warning of warnings) { |
| 209 | + expect(warning.length).toBeLessThanOrEqual(2_200); |
| 210 | + expect(hasTerminalControl(warning)).toBe(false); |
| 211 | + expect(warning).not.toMatch(/[\uD800-\uDFFF]/u); |
| 212 | + expect(warning).not.toContain(credential); |
| 213 | + expect(warning).not.toContain(capturedText); |
| 214 | + expect(warning).not.toContain('"transcript":'); |
| 215 | + } |
| 216 | + } |
| 217 | + } finally { |
| 218 | + for (const gate of gates.values()) { |
| 219 | + gate.resolve(); |
| 220 | + } |
| 221 | + await service.stop(); |
| 222 | + // Thrown provider stops retain capture ownership; clean up via the public tool. |
| 223 | + for (const id of requests.keys()) { |
| 224 | + await execute("stop", id); |
| 225 | + } |
| 226 | + } |
| 227 | + }); |
| 228 | + }); |
| 229 | +}); |
0 commit comments