Skip to content

Commit 8b0ccce

Browse files
committed
fix(transcripts): report auto-start shutdown warnings
Configured captures now report failed summary exports and provider-stop warnings while preserving saved notes and sibling cleanup. Refs #131375.
1 parent 456dd3e commit 8b0ccce

3 files changed

Lines changed: 277 additions & 17 deletions

File tree

‎docs/cli/transcripts.md‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,15 +103,23 @@ when it will not repeat on the same date.
103103

104104
## Missing summaries
105105

106-
Live sessions store and materialize `summary.md` when the session stops;
107-
imported transcripts do so immediately after import. A session can appear in
108-
`list` without a summary while capture is still active, if a provider failed
109-
during stop, or if metadata was stored before any utterances arrived.
106+
Live sessions save summaries when capture stops; imported transcripts do so
107+
immediately after import. Tool-driven stops, configured auto-start shutdown, and
108+
imports also attempt to materialize `summary.md`. A session can appear in `list`
109+
without a summary while capture is still active, if a provider failed during stop,
110+
or if metadata was stored before any utterances arrived.
110111

111112
Use `path <session> --transcript` to inspect the raw append-only transcript,
112113
or run the `transcripts` tool's `summarize` action to regenerate the Markdown
113114
summary.
114115

116+
Summaries are saved in SQLite before optional artifact export. If export fails,
117+
the saved summary remains available even when `summary.md` is missing. Configured
118+
auto-start captures log warnings during shutdown for failed exports or provider
119+
stop errors. Correct the export destination problem, then run
120+
`openclaw transcripts path <session>` or `openclaw transcripts show <session>`
121+
to retry the export; an intended path in a warning is not proof of an exported file.
122+
115123
Historical sessions without complete account-owner metadata remain on a local
116124
recovery path. Recover an agent-owned row with a local turn for that agent; a row
117125
with no agent attribution requires a local main-agent turn. Sources without
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
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+
});

‎src/agents/tools/transcripts-tool.ts‎

Lines changed: 36 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,10 @@ import path from "node:path";
77
import { asOptionalRecord } from "@openclaw/normalization-core/record-coerce";
88
import { uniqueStrings } from "@openclaw/normalization-core/string-normalization";
99
import { Type } from "typebox";
10+
import { sanitizeTerminalText } from "../../../packages/terminal-core/src/safe-text.js";
1011
import { resolveStateDir } from "../../config/paths.js";
1112
import type { OpenClawConfig } from "../../config/types.openclaw.js";
13+
import { formatErrorMessage } from "../../infra/errors.js";
1214
import {
1315
type ResolvedTranscriptsAutoStartConfig,
1416
resolveTranscriptsConfig,
@@ -22,6 +24,7 @@ import type {
2224
import { sanitizeTranscriptSourceLocator } from "../../transcripts/source-locator.js";
2325
import { TranscriptsStore, type TranscriptsSessionEntry } from "../../transcripts/store.js";
2426
import { summarizeTranscripts } from "../../transcripts/summary.js";
27+
import { truncateUtf16Safe } from "../../utils.js";
2528
import type { AnyAgentTool } from "./common.js";
2629
import {
2730
activeSessions,
@@ -42,6 +45,10 @@ const AUTO_START_RETRY_MS = 5_000;
4245
const AUTO_START_STOP_TIMEOUT_MS = 5_000;
4346
const AUTO_START_PROVIDER_READY_TIMEOUT_MS = 30_000;
4447

48+
function formatAutoStopDiagnostic(value: unknown): string {
49+
return JSON.stringify(truncateUtf16Safe(sanitizeTerminalText(formatErrorMessage(value)), 300));
50+
}
51+
4552
type TranscriptSessionIdentity = Pick<TranscriptSessionDescriptor, "sessionId" | "startedAt">;
4653

4754
function sameSessionIdentity(
@@ -582,20 +589,36 @@ export function createTranscriptsAutoStartService(ctx: TranscriptsRuntimeContext
582589
}
583590
const store = createStore(ctx);
584591
for (const [sessionId, lifecycleToken] of startedSessions) {
585-
await stopTranscripts({
586-
ctx,
587-
store,
588-
rawParams: { action: "stop", sessionId },
589-
// Bypass authorization only while the exact capture created by this
590-
// service is still active; a reused id may belong to another owner.
591-
lifecycleToken,
592-
}).catch((err: unknown) =>
592+
const warnings: string[] = [];
593+
try {
594+
const { details } = await stopTranscripts({
595+
ctx,
596+
store,
597+
rawParams: { action: "stop", sessionId },
598+
// Bypass authorization only while the exact capture created by this
599+
// service is still active; a reused id may belong to another owner.
600+
lifecycleToken,
601+
});
602+
// Fulfillment can include partial success; only diagnostics belong in logs,
603+
// never the tool content or summary. Skipped captures have no warnings.
604+
if (typeof details.summaryExportError === "string") {
605+
warnings.push(
606+
`summary saved; export failed intendedSummaryPath=${formatAutoStopDiagnostic(details.intendedSummaryPath)}: ${formatAutoStopDiagnostic(details.summaryExportError)}. Correct the export destination, then run openclaw transcripts path <session> or openclaw transcripts show <session>.`,
607+
);
608+
}
609+
if (typeof details.providerStopError === "string") {
610+
warnings.push(
611+
`provider stop failed: ${formatAutoStopDiagnostic(details.providerStopError)}. Check the provider capture status and connection.`,
612+
);
613+
}
614+
} catch (error) {
615+
warnings.push(`stop failed: ${formatAutoStopDiagnostic(error)}`);
616+
}
617+
for (const warning of warnings) {
593618
ctx.logger.warn(
594-
`transcripts autoStart stop failed session=${sessionId}: ${
595-
err instanceof Error ? err.message : String(err)
596-
}`,
597-
),
598-
);
619+
`transcripts autoStart session=${formatAutoStopDiagnostic(sessionId)}: ${warning}`,
620+
);
621+
}
599622
}
600623
startedSessions.clear();
601624
},

0 commit comments

Comments
 (0)