Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

improve trace upload reliability and controls (#389)

ktc514ab9652c1
diff --git a/packages/coding-agent/CHANGELOG.md b/packages/coding-agent/CHANGELOG.md
index 67bb85e391..fd70e17f5b 100644
--- a/packages/coding-agent/CHANGELOG.md
+++ b/packages/coding-agent/CHANGELOG.md
@@ -7,6 +7,7 @@
- Changed shell commands to use discoverable agent, schedule, package, model, session, update, doctor, and full-shutdown verbs without exposing the background daemon hierarchy ([ENG-4538](https://linear.app/primeintellect/issue/ENG-4538/standardize-bash-command-conventions-and-improve-command-discovery)).
- Fixed unsupported Node versions crashing before startup by requiring Node 22.8.0 or newer and showing upgrade guidance before loading the CLI ([ENG-4260](https://linear.app/primeintellect/issue/ENG-4260/incorrect-node-version-breaks-first-launch)).
- Added `@` file-path autocomplete to new-agent and reply prompts in the Agents View.
+- Changed `/traces upload-all` to pace requests within the platform rate limit, honor bounded `Retry-After` responses, and support interruption.
- Fixed resuming a daemon-resident session to attach the requesting client to its existing worker without disturbing other clients ([ENG-4656](https://linear.app/primeintellect/issue/ENG-4656/resuming-prime-agent-sessions-should-attach)).
- Fixed daemon-owned updates terminating their updater before the daemon restart and session restore completed ([ENG-4606](https://linear.app/primeintellect/issue/ENG-4606/benign-error-on-prime-agent-update)).
- Fixed first-launch Prime login and kept onboarding visible between team and model selection ([ENG-4658](https://linear.app/primeintellect/issue/ENG-4658/fix-onboarding-login-enter-key-and-model-selector-flicker)).
@@ -43,6 +44,9 @@
- Changed daemon and headless execution to isolate each root session tree in a recoverable worker process, with protocol-v2 chunked snapshots, compact streaming, attachment-local backpressure, session leases, and unchanged print, JSON, and RPC interfaces.
- Added autonomous mode with host-side continuations, configurable limits, and quality gates for evaluator-controlled runs ([#278](https://github.com/PrimeIntellect-ai/prime-agent/pull/278) by [@sethkarten](https://github.com/sethkarten)).
+- Added `/traces preview` and `/traces upload-all` for inspecting the current payload and backfilling saved parent and subagent traces.
+- Changed `/traces upload` and `/traces upload-all` to be explicit one-shot uploads that do not enable automatic sharing.
+- Changed trace uploads to retry transient network and HTTP failures with bounded exponential backoff and jitter.
- Fixed Prime Inference credential and team-header precedence to prefer `PRIME_API_KEY`, then the Prime CLI config, then `auth.json`.
- Fixed aborted autonomous gates leaving detached process trees and supervisor recovery retaining intentionally stopped workers after stale scheduler locks.
- Fixed supervisor replacement surfacing fatal socket errors or recovering roots that were intentionally stopped ([ENG-4526](https://linear.app/primeintellect/issue/ENG-4526/reconnect-daemon-clients-transparently-after-supervisor-replacement)).
diff --git a/packages/coding-agent/README.md b/packages/coding-agent/README.md
index 84ab805b9c..1ae2d90100 100644
--- a/packages/coding-agent/README.md
+++ b/packages/coding-agent/README.md
@@ -148,7 +148,7 @@ Type `/` in the editor to trigger commands. [Extensions](#extensions) can regist
| `/new`, `/clear` | Start a new session |
| `/name <name>` | Set session display name |
| `/session` | Show session info (file, ID, messages) |
-| `/traces [status\|on\|off\|upload\|login]` | Manage opt-in Prime Agent trace sharing |
+| `/traces [status\|on\|off\|preview\|upload-current\|upload-all\|login]` | Preview traces, run one-shot current/all uploads, and manage automatic sharing (`upload` aliases `upload-current`) |
| `/usage` | Show token, cost, and context usage |
| `/tree` | Jump to any point in the session and continue from there |
| `/fork` | Create a new session from a previous user message |
diff --git a/packages/coding-agent/src/core/agent-traces.ts b/packages/coding-agent/src/core/agent-traces.ts
index 160a706aa1..fb00b8aca8 100644
--- a/packages/coding-agent/src/core/agent-traces.ts
+++ b/packages/coding-agent/src/core/agent-traces.ts
@@ -1,7 +1,8 @@
import { Buffer } from "node:buffer";
-import { readFile, stat } from "node:fs/promises";
-import { dirname, isAbsolute, resolve } from "node:path";
-import { appendRotatingLog, getAgentTracesLogPath, VERSION } from "../config.js";
+import type { Dirent } from "node:fs";
+import { readdir, readFile, stat } from "node:fs/promises";
+import { dirname, isAbsolute, join, resolve } from "node:path";
+import { appendRotatingLog, getAgentTracesLogPath, getSessionsDir, VERSION } from "../config.js";
import { readFirstLineSync } from "../utils/file-lines.js";
import type { AuthStorage } from "./auth-storage.js";
import {
@@ -17,7 +18,17 @@ const MAX_TRACE_BYTES = 20 * 1024 * 1024;
const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
const TRACE_UPLOAD_DEBOUNCE_MS = 1_000;
const TRACE_UPLOAD_MIN_INTERVAL_MS = 60_000;
-const TRACE_UPLOAD_RETRY_DELAY_MS = 500;
+const TRACE_UPLOAD_RETRY_BASE_DELAY_MS = 500;
+const TRACE_UPLOAD_RETRY_MAX_DELAY_MS = 10_000;
+const TRACE_UPLOAD_MAX_RETRIES = 3;
+const TRACE_UPLOAD_RETRY_JITTER = 0.2;
+const TRACE_PREVIEW_MAX_CHARS = 8_000;
+const TRACE_UPLOAD_ALL_CONCURRENCY = 4;
+const TRACE_UPLOAD_RATE_LIMIT_REQUESTS = 5;
+const TRACE_UPLOAD_RATE_LIMIT_WINDOW_MS = 60_000;
+const TRACE_UPLOAD_RATE_LIMIT_SAFETY_MS = 100;
+const TRACE_UPLOAD_ALL_MIN_REQUEST_INTERVAL_MS =
+ Math.ceil(TRACE_UPLOAD_RATE_LIMIT_WINDOW_MS / TRACE_UPLOAD_RATE_LIMIT_REQUESTS) + TRACE_UPLOAD_RATE_LIMIT_SAFETY_MS;
export type AgentTraceCredentialSource = "environment" | "stored" | "prime-inference" | "prime-cli";
@@ -47,6 +58,8 @@ export interface AgentTraceUploadOptions {
sessionFile: string | undefined;
authStorage: AuthStorage;
settingsManager: SettingsManager;
+ /** Require the global automatic-sharing opt-in. Set false only for an explicit one-shot upload command. */
+ requireEnabled?: boolean;
baseUrl?: string;
configPath?: string;
fetchFn?: typeof fetch;
@@ -68,6 +81,56 @@ export interface AgentTraceUploadInstallOptions {
requestTimeoutMs?: number;
}
+export type AgentTracePreviewResult =
+ | {
+ status: "ready";
+ sessionFile: string;
+ sessionId: string;
+ traceId: string;
+ parentSessionId?: string;
+ cwd: string;
+ size: number;
+ maxBytes: number;
+ uploadable: boolean;
+ endpoint: string;
+ gitRepo?: string;
+ gitCommit?: string;
+ contentPreview: string;
+ truncated: boolean;
+ }
+ | { status: "no_session_file" }
+ | { status: "empty_session" }
+ | { status: "invalid_session"; message: string }
+ | { status: "failed"; message: string };
+
+export interface AgentTracePreviewOptions {
+ sessionFile: string | undefined;
+ baseUrl?: string;
+ maxContentChars?: number;
+}
+
+export interface AgentTraceUploadAllProgress {
+ completed: number;
+ total: number;
+ sessionFile?: string;
+ result?: AgentTraceUploadResult;
+}
+
+export interface AgentTraceUploadAllOptions extends Omit<AgentTraceUploadOptions, "sessionFile"> {
+ sessionDir?: string;
+ concurrency?: number;
+ onProgress?: (progress: AgentTraceUploadAllProgress) => void;
+}
+
+export interface AgentTraceUploadAllResult {
+ total: number;
+ uploaded: number;
+ failed: number;
+ skipped: number;
+ bytesStored: number;
+ results: Array<{ sessionFile: string; result: AgentTraceUploadResult }>;
+}
+
function stringEnv(name: string): string | undefined {
const value = process.env[name];
return typeof value === "string" && value.trim() ? value.trim() : undefined;
@@ -93,6 +156,13 @@ function describeError(error: unknown): string {
return error.message;
}
+class TraceUploadTimeoutError extends Error {
+ constructor(timeoutMs: number) {
+ super(`Trace upload timed out after ${timeoutMs}ms`);
+ this.name = "TraceUploadTimeoutError";
+ }
+}
+
const RETRIABLE_NETWORK_CODES = new Set([
"ECONNRESET",
"ECONNREFUSED",
@@ -106,7 +176,12 @@ const RETRIABLE_NETWORK_CODES = new Set([
"UND_ERR_CONNECT_TIMEOUT",
]);
+const RETRIABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);
+
function isRetriableNetworkError(error: unknown): boolean {
+ if (error instanceof TraceUploadTimeoutError) {
+ return true;
+ }
if (!(error instanceof Error) || error.name === "AbortError") {
return false;
}
@@ -260,12 +335,26 @@ async function fetchWithTimeout(
signal?: AbortSignal,
): Promise<Response> {
const controller = new AbortController();
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
- const onAbort = () => controller.abort();
- signal?.addEventListener("abort", onAbort, { once: true });
+ const timeoutError = new TraceUploadTimeoutError(timeoutMs);
+ let timedOut = false;
+ const timeout = setTimeout(() => {
+ timedOut = true;
+ controller.abort(timeoutError);
+ }, timeoutMs);
+ const onAbort = () => controller.abort(signal?.reason);
+ if (signal?.aborted) {
+ onAbort();
+ } else {
+ signal?.addEventListener("abort", onAbort, { once: true });
+ }
try {
return await fetchFn(url, { ...init, signal: controller.signal });
+ } catch (error) {
+ if (timedOut) {
+ throw timeoutError;
+ }
+ throw error;
} finally {
clearTimeout(timeout);
signal?.removeEventListener("abort", onAbort);
@@ -274,6 +363,10 @@ async function fetchWithTimeout(
function delay(ms: number, signal?: AbortSignal): Promise<void> {
return new Promise((resolve) => {
+ if (signal?.aborted) {
+ resolve();
+ return;
+ }
const timeout = setTimeout(finish, ms);
const onAbort = () => finish();
function finish() {
@@ -285,28 +378,258 @@ function delay(ms: number, signal?: AbortSignal): Promise<void> {
});
}
+function traceUploadRetryDelay(retryIndex: number): number {
+ const exponentialDelay = Math.min(
+ TRACE_UPLOAD_RETRY_MAX_DELAY_MS,
+ TRACE_UPLOAD_RETRY_BASE_DELAY_MS * 2 ** retryIndex,
+ );
+ const jitterMultiplier = 1 - TRACE_UPLOAD_RETRY_JITTER + Math.random() * TRACE_UPLOAD_RETRY_JITTER * 2;
+ return Math.max(0, Math.round(exponentialDelay * jitterMultiplier));
+}
+
+function retryAfterDelay(response: Response): number | undefined {
+ const value = response.headers.get("retry-after")?.trim();
+ if (!value) {
+ return undefined;
+ }
+ const seconds = Number(value);
+ if (Number.isFinite(seconds) && seconds >= 0) {
+ return Math.min(Math.ceil(seconds * 1_000), TRACE_UPLOAD_RATE_LIMIT_WINDOW_MS);
+ }
+ const retryAt = Date.parse(value);
+ return Number.isFinite(retryAt)
+ ? Math.min(Math.max(0, retryAt - Date.now()), TRACE_UPLOAD_RATE_LIMIT_WINDOW_MS)
+ : undefined;
+}
+
+type BeforeTraceUploadRequest = () => Promise<void>;
+
async function fetchWithRetry(
fetchFn: typeof fetch,
url: string,
init: RequestInit,
timeoutMs: number,
signal?: AbortSignal,
+ beforeRequest?: BeforeTraceUploadRequest,
): Promise<Response> {
- try {
- return await fetchWithTimeout(fetchFn, url, init, timeoutMs, signal);
- } catch (error) {
+ for (let attempt = 0; ; attempt += 1) {
+ let retryDelayMs: number | undefined;
+ try {
+ await beforeRequest?.();
+ if (signal?.aborted) {
+ throw signal.reason ?? new Error("Trace upload cancelled");
+ }
+ const response = await fetchWithTimeout(fetchFn, url, init, timeoutMs, signal);
+ if (attempt >= TRACE_UPLOAD_MAX_RETRIES || !RETRIABLE_HTTP_STATUSES.has(response.status)) {
+ return response;
+ }
+ if (response.status === 429) {
+ retryDelayMs = retryAfterDelay(response) ?? TRACE_UPLOAD_RATE_LIMIT_WINDOW_MS;
+ } else if (response.status === 503) {
+ retryDelayMs = retryAfterDelay(response);
+ }
+ await response.body?.cancel().catch(() => undefined);
+ } catch (error) {
+ if (signal?.aborted) {
+ throw signal.reason ?? error;
+ }
+ if (attempt >= TRACE_UPLOAD_MAX_RETRIES || !isRetriableNetworkError(error)) {
+ throw error;
+ }
+ }
+
+ await delay(retryDelayMs ?? traceUploadRetryDelay(attempt), signal);
if (signal?.aborted) {
- throw signal.reason ?? error;
+ throw signal.reason ?? new Error("Trace upload cancelled");
}
- if (!isRetriableNetworkError(error)) {
- throw error;
+ }
+}
+
+function traceContentPreview(body: string, maxChars: number): { content: string; truncated: boolean } {
+ if (body.length <= maxChars) {
+ return { content: body.trimEnd(), truncated: false };
+ }
+ const marker = "\n... middle of trace omitted ...\n";
+ const available = Math.max(0, maxChars - marker.length);
+ const headChars = Math.ceil(available / 2);
+ const tailChars = Math.floor(available / 2);
+ return {
+ content: `${body.slice(0, headChars).trimEnd()}${marker}${body.slice(body.length - tailChars).trimStart()}`,
+ truncated: true,
+ };
+}
+
+export async function previewAgentTraceFile(options: AgentTracePreviewOptions): Promise<AgentTracePreviewResult> {
+ if (!options.sessionFile) {
+ return { status: "no_session_file" };
+ }
+
+ let fileSize: number;
+ try {
+ const stats = await stat(options.sessionFile);
+ if (!stats.isFile()) {
+ return { status: "no_session_file" };
}
- await delay(TRACE_UPLOAD_RETRY_DELAY_MS, signal);
- if (signal?.aborted) {
- throw signal.reason ?? error;
+ fileSize = stats.size;
+ } catch {
+ return { status: "no_session_file" };
+ }
+ if (fileSize === 0) {
+ return { status: "empty_session" };
+ }
+
+ const header = readSessionHeader(options.sessionFile);
+ if (!header) {
+ return { status: "invalid_session", message: "Session file is missing a valid session header" };
+ }
+
+ let body = "";
+ if (fileSize <= MAX_TRACE_BYTES) {
+ try {
+ body = await readFile(options.sessionFile, "utf8");
+ } catch (error) {
+ return { status: "failed", message: describeError(error) };
+ }
+ if (!body.trim()) {
+ return { status: "empty_session" };
+ }
+ }
+
+ const traceContext = resolveTraceContext(options.sessionFile, header);
+ const baseUrl = resolvePrimeAgentTracesBaseUrl(options.baseUrl);
+ const git = body ? activeGitContext(body, header) : header.git;
+ const preview = body
+ ? traceContentPreview(body, Math.max(256, options.maxContentChars ?? TRACE_PREVIEW_MAX_CHARS))
+ : { content: "", truncated: true };
+ return {
+ status: "ready",
+ sessionFile: options.sessionFile,
+ sessionId: header.id,
+ traceId: traceContext.traceId,
+ parentSessionId: traceContext.parentSessionId,
+ cwd: header.cwd,
+ size: fileSize,
+ maxBytes: MAX_TRACE_BYTES,
+ uploadable: fileSize <= MAX_TRACE_BYTES,
+ endpoint: `${baseUrl}/api/v1/agent-traces/sessions/${encodeURIComponent(header.id)}`,
+ gitRepo: git?.repoUrl,
+ gitCommit: git?.commit,
+ contentPreview: preview.content,
+ truncated: preview.truncated,
+ };
+}
+
+async function findSessionFilesUnder(root: string, files: Set<string>): Promise<void> {
+ let entries: Dirent[];
+ try {
+ entries = await readdir(root, { withFileTypes: true });
+ } catch {
+ return;
+ }
+
+ for (const entry of entries) {
+ const entryPath = join(root, entry.name);
+ if (entry.isDirectory()) {
+ await findSessionFilesUnder(entryPath, files);
+ continue;
+ }
+ if (entry.isFile() && entry.name.endsWith(".jsonl") && readSessionHeader(entryPath)) {
+ files.add(entryPath);
+ }
+ }
+}
+
+export async function findAgentTraceFiles(sessionDir: string = getSessionsDir()): Promise<string[]> {
+ const files = new Set<string>();
+ const roots = new Set([resolve(sessionDir), resolve(dirname(sessionDir), "session-artifacts")]);
+ await Promise.all([...roots].map((root) => findSessionFilesUnder(root, files)));
+ return [...files].sort();
+}
+
+function createTraceUploadAllRequestGate(signal?: AbortSignal): BeforeTraceUploadRequest {
+ let nextRequestAt = 0;
+ let queue = Promise.resolve();
+ return () => {
+ const slot = queue.then(async () => {
+ const waitMs = Math.max(0, nextRequestAt - Date.now());
+ if (waitMs > 0) {
+ await delay(waitMs, signal);
+ }
+ if (!signal?.aborted) {
+ nextRequestAt = Date.now() + TRACE_UPLOAD_ALL_MIN_REQUEST_INTERVAL_MS;
+ }
+ });
+ queue = slot.catch(() => undefined);
+ return slot;
+ };
+}
+
+export async function uploadAllAgentTraces(options: AgentTraceUploadAllOptions): Promise<AgentTraceUploadAllResult> {
+ const { sessionDir, concurrency, onProgress, ...uploadOptions } = options;
+ const sessionFiles = await findAgentTraceFiles(sessionDir);
+ type UploadResultItem = AgentTraceUploadAllResult["results"][number];
+ const results: Array<UploadResultItem | undefined> = new Array(sessionFiles.length);
+ let cursor = 0;
+ let completed = 0;
+ const beforeRequest = createTraceUploadAllRequestGate(uploadOptions.signal);
+ onProgress?.({ completed, total: sessionFiles.length });
+
+ const worker = async () => {
+ while (true) {
+ if (uploadOptions.signal?.aborted) {
+ return;
+ }
+ const index = cursor;
+ cursor += 1;
+ const sessionFile = sessionFiles[index];
+ if (!sessionFile) {
+ return;
+ }
+ const result = await uploadAgentTraceFileWithRequestGate(
+ {
+ ...uploadOptions,
+ sessionFile,
+ reloadConfig: false,
+ },
+ beforeRequest,
+ );
+ if (uploadOptions.signal?.aborted && result.status === "failed") {
+ return;
+ }
+ results[index] = { sessionFile, result };
+ completed += 1;
+ onProgress?.({ completed, total: sessionFiles.length, sessionFile, result });
+ }
+ };
+
+ const requestedConcurrency = concurrency ?? TRACE_UPLOAD_ALL_CONCURRENCY;
+ const normalizedConcurrency =
+ Number.isFinite(requestedConcurrency) && requestedConcurrency > 0
+ ? Math.max(1, Math.floor(requestedConcurrency))
+ : TRACE_UPLOAD_ALL_CONCURRENCY;
+ const workerCount = Math.min(sessionFiles.length, normalizedConcurrency);
+ await Promise.all(Array.from({ length: workerCount }, worker));
+
+ const completedResults = results.filter((item): item is UploadResultItem => item !== undefined);
+ let uploaded = 0;
+ let failed = 0;
+ let bytesStored = 0;
+ for (const item of completedResults) {
+ if (item.result.status === "uploaded") {
+ uploaded += 1;
+ bytesStored += item.result.bytesStored;
+ } else if (item.result.status === "failed") {
+ failed += 1;
}
- return await fetchWithTimeout(fetchFn, url, init, timeoutMs, signal);
}
+ return {
+ total: sessionFiles.length,
+ uploaded,
+ failed,
+ skipped: sessionFiles.length - uploaded - failed,
+ bytesStored,
+ results: completedResults,
+ };
}
export async function getPrimeAgentTraceCredential(
@@ -357,12 +680,19 @@ async function getAgentTracesEnabled(
return options.settingsManager.getAgentTracesEnabled();
}
-export async function uploadAgentTraceFile(options: AgentTraceUploadOptions): Promise<AgentTraceUploadResult> {
- const result = await performAgentTraceUpload(options);
+async function uploadAgentTraceFileWithRequestGate(
+ options: AgentTraceUploadOptions,
+ beforeRequest?: BeforeTraceUploadRequest,
+): Promise<AgentTraceUploadResult> {
+ const result = await performAgentTraceUpload(options, beforeRequest);
logAgentTraceOutcome(options.sessionFile, result);
return result;
}
+export function uploadAgentTraceFile(options: AgentTraceUploadOptions): Promise<AgentTraceUploadResult> {
+ return uploadAgentTraceFileWithRequestGate(options);
+}
+
function logAgentTraceOutcome(sessionFile: string | undefined, result: AgentTraceUploadResult): void {
let line: string | undefined;
switch (result.status) {
@@ -388,8 +718,12 @@ function logAgentTraceOutcome(sessionFile: string | undefined, result: AgentTrac
appendRotatingLog(getAgentTracesLogPath(), `[${new Date().toISOString()}] ${line}${suffix}`);
}
-async function performAgentTraceUpload(options: AgentTraceUploadOptions): Promise<AgentTraceUploadResult> {
- if (!(await getAgentTracesEnabled(options))) {
+async function performAgentTraceUpload(
+ options: AgentTraceUploadOptions,
+ beforeRequest?: BeforeTraceUploadRequest,
+): Promise<AgentTraceUploadResult> {
+ const requireEnabled = options.requireEnabled !== false;
+ if (requireEnabled && !(await getAgentTracesEnabled(options))) {
return { status: "disabled" };
}
if (!options.sessionFile) {
@@ -426,7 +760,7 @@ async function performAgentTraceUpload(options: AgentTraceUploadOptions): Promis
return { status: "missing_credentials" };
}
- if (!(await getAgentTracesEnabled(options))) {
+ if (requireEnabled && !(await getAgentTracesEnabled(options))) {
return { status: "disabled" };
}
@@ -461,7 +795,7 @@ async function performAgentTraceUpload(options: AgentTraceUploadOptions): Promis
headers["X-Git-Commit"] = git.commit;
}
- if (!(await getAgentTracesEnabled(options))) {
+ if (requireEnabled && !(await getAgentTracesEnabled(options))) {
return { status: "disabled" };
}
@@ -481,6 +815,7 @@ async function performAgentTraceUpload(options: AgentTraceUploadOptions): Promis
},
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
options.signal,
+ beforeRequest,
);
} catch (error) {
return { status: "failed", message: describeError(error) };
diff --git a/packages/coding-agent/src/core/slash-commands.ts b/packages/coding-agent/src/core/slash-commands.ts
index d0d4d5affa..ade16ac5fa 100644
--- a/packages/coding-agent/src/core/slash-commands.ts
+++ b/packages/coding-agent/src/core/slash-commands.ts
@@ -57,8 +57,8 @@ const CANONICAL_BUILTIN_SLASH_COMMANDS: ReadonlyArray<BuiltinSlashCommand> = [
{ name: "logs", description: "Show where daemon and client logs are saved" },
{
name: "traces",
- description: "Opt in or out of Prime Agent trace sharing",
- argumentHint: "[status|on|off|upload|login]",
+ description: "Preview, upload, or configure Prime Agent traces",
+ argumentHint: "[status|on|off|preview|upload|upload-current|upload-all|login]",
},
{ name: "context", description: "Show token, cost, and context usage for agent and sub-agents" },
{ name: "changelog", description: "Show changelog entries" },
diff --git a/packages/coding-agent/src/modes/interactive/interactive-mode.ts b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
index dd9b9e71b0..df0b74f879 100644
--- a/packages/coding-agent/src/modes/interactive/interactive-mode.ts
+++ b/packages/coding-agent/src/modes/interactive/interactive-mode.ts
@@ -68,9 +68,13 @@ import {
} from "../../config.js";
import { AGENT_MESSAGE_RECEIVED_PREVIEW_LABEL, isAgentSessionMessage } from "../../core/agent-messages.js";
import {
+ type AgentTracePreviewResult,
+ type AgentTraceUploadAllResult,
type AgentTraceUploadResult,
getPrimeAgentTraceCredential,
+ previewAgentTraceFile,
uploadAgentTraceFile,
+ uploadAllAgentTraces,
} from "../../core/agent-traces.js";
import { isNoModelsAvailableMessage } from "../../core/auth-guidance.js";
import {
@@ -837,6 +841,7 @@ export class InteractiveMode {
// Auto-retry state
private retryLoader: Loader | undefined = undefined;
private retryCountdown: CountdownTimer | undefined = undefined;
+ private traceUploadAllAbortController: AbortController | undefined = undefined;
// Messages queued while compaction is running
private compactionQueuedMessages: CompactionQueuedMessage[] = [];
@@ -2495,6 +2500,7 @@ export class InteractiveMode {
this.isAgentCompacting() ||
this.isBashRunning() ||
this.getRetryAttempt() > 0 ||
+ this.traceUploadAllAbortController !== undefined ||
this.sideQuestionEvent?.status === "running"
);
}
@@ -6039,6 +6045,7 @@ export class InteractiveMode {
}
private interruptOrClearInput(): void {
+ this.traceUploadAllAbortController?.abort(new Error("Trace upload cancelled"));
if (this.sideQuestionEvent?.status === "running") {
this.abortSideQuestion(this.sideQuestionEvent.id, true);
}
@@ -8378,9 +8385,9 @@ export class InteractiveMode {
case "missing_credentials":
return "Trace sharing needs a Prime API key. Run /traces login.";
case "no_session_file":
- return "Trace sharing enabled. Current session will upload after the first assistant response.";
+ return "Current session has no persisted trace yet.";
case "empty_session":
- return "Trace sharing enabled. Current session is empty.";
+ return "Current session trace is empty.";
case "invalid_session":
return `Trace upload skipped: ${result.message}.`;
case "too_large":
@@ -8399,10 +8406,86 @@ export class InteractiveMode {
sessionFile: state.sessionFile,
authStorage: this.modelRegistry.authStorage,
settingsManager: this.settingsManager,
+ requireEnabled: false,
reloadConfig: false,
});
}
+ private async previewCurrentTrace(): Promise<void> {
+ const state = await this.agentConnection.getState();
+ const result = await previewAgentTraceFile({ sessionFile: state.sessionFile });
+ let info: string;
+ switch (result.status) {
+ case "no_session_file":
+ info = "Trace preview is unavailable until the current session has a persisted assistant response.";
+ break;
+ case "empty_session":
+ info = "The current trace is empty.";
+ break;
+ case "invalid_session":
+ case "failed":
+ info = `Trace preview failed: ${result.message}.`;
+ break;
+ case "ready":
+ info = this.formatTracePreview(result);
+ break;
+ }
+ this.chatContainer.addChild(new Spacer(1));
+ this.chatContainer.addChild(new Text(info, 1, 0));
+ this.ui.requestRender();
+ }
+
+ private formatTracePreview(result: Extract<AgentTracePreviewResult, { status: "ready" }>): string {
+ const lines = [
+ theme.bold("Trace Preview"),
+ theme.fg("dim", "Nothing has been uploaded by this command."),
+ "",
+ `${theme.fg("dim", "File:")} ${result.sessionFile}`,
+ `${theme.fg("dim", "Size:")} ${result.size.toLocaleString()} bytes`,
+ `${theme.fg("dim", "Uploadable:")} ${result.uploadable ? "Yes" : `No (limit ${result.maxBytes.toLocaleString()} bytes)`}`,
+ `${theme.fg("dim", "Endpoint:")} ${result.endpoint}`,
+ `${theme.fg("dim", "Session ID:")} ${result.sessionId}`,
+ `${theme.fg("dim", "Trace ID:")} ${result.traceId}`,
+ ];
+ if (result.parentSessionId) {
+ lines.push(`${theme.fg("dim", "Parent session:")} ${result.parentSessionId}`);
+ }
+ if (result.gitRepo) {
+ lines.push(`${theme.fg("dim", "Git repository:")} ${result.gitRepo}`);
+ }
+ if (result.gitCommit) {
+ lines.push(`${theme.fg("dim", "Git commit:")} ${result.gitCommit}`);
+ }
+ lines.push("", theme.bold("Raw JSONL payload preview"));
+ if (result.contentPreview) {
+ lines.push(result.contentPreview);
+ if (result.truncated) {
+ lines.push("", theme.fg("dim", "Preview truncated; upload sends the complete file."));
+ }
+ } else {
+ lines.push(theme.fg("dim", "Payload omitted because the trace exceeds the upload limit."));
+ }
+ return lines.join("\n");
+ }
+
+ private async uploadAllTraces(sessionDir?: string, signal?: AbortSignal): Promise<AgentTraceUploadAllResult> {
+ return uploadAllAgentTraces({
+ authStorage: this.modelRegistry.authStorage,
+ settingsManager: this.settingsManager,
+ sessionDir,
+ requireEnabled: false,
+ reloadConfig: false,
+ signal,
+ onProgress: ({ completed, total }) => {
+ if (total > 0 && (completed === 0 || completed === total || completed % 10 === 0)) {
+ this.showStatus(
+ `Uploading traces: ${completed.toLocaleString()}/${total.toLocaleString()} (${keyText("app.clear")} to cancel)`,
+ );
+ }
+ },
+ });
+ }
+
private async handleTracesCommand(text: string): Promise<void> {
const command =
text
@@ -8417,12 +8500,15 @@ export class InteractiveMode {
const info = [
theme.bold("Trace Sharing"),
"",
- `${theme.fg("dim", "Status:")} ${this.settingsManager.getAgentTracesEnabled() ? "Enabled" : "Disabled"}`,
+ `${theme.fg("dim", "Automatic uploads:")} ${this.settingsManager.getAgentTracesEnabled() ? "Enabled" : "Disabled"}`,
`${theme.fg("dim", "Credential:")} ${credential?.label ?? "Not configured"}`,
`${theme.fg("dim", "Endpoint:")} ${resolvePrimeAgentTracesBaseUrl()}`,
`${theme.fg("dim", "Session file:")} ${state.sessionFile ?? "In-memory"}`,
"",
- theme.fg("dim", "Commands: /traces on, /traces off, /traces upload, /traces login"),
+ theme.fg(
+ "dim",
+ "Commands: /traces on, /traces off, /traces preview, /traces upload-current, /traces upload-all, /traces login",
+ ),
].join("\n");
this.chatContainer.addChild(new Spacer(1));
this.chatContainer.addChild(new Text(info, 1, 0));
@@ -8442,6 +8528,11 @@ export class InteractiveMode {
return;
}
+ if (command === "preview") {
+ await this.previewCurrentTrace();
+ return;
+ }
+
if (command === "on" || command === "enable") {
let credential = await getPrimeAgentTraceCredential(this.modelRegistry.authStorage);
if (!credential) {
@@ -8459,18 +8550,18 @@ export class InteractiveMode {
this.settingsManager.setAgentTracesEnabled(true);
await this.settingsManager.flush();
const uploadResult = await this.uploadCurrentTraceOnce();
- const uploadMessage = this.formatTraceUploadResult(uploadResult);
- this.showStatus(
+ const uploadMessage =
uploadResult.status === "no_session_file" || uploadResult.status === "empty_session"
- ? uploadMessage
- : `Trace sharing enabled. ${uploadMessage}`,
- );
+ ? "Current session will upload after the first assistant response."
+ : this.formatTraceUploadResult(uploadResult);
+ this.showStatus(`Trace sharing enabled. ${uploadMessage}`);
return;
}
- if (command === "upload") {
- if (!this.settingsManager.getAgentTracesEnabled()) {
- this.showStatus("Trace sharing is disabled. Run /traces on first.");
+ if (command === "upload" || command === "upload-current") {
+ const credential = await getPrimeAgentTraceCredential(this.modelRegistry.authStorage);
+ if (!credential) {
+ this.showError("Trace sharing needs a Prime API key. Run /traces login.");
return;
}
const uploadResult = await this.uploadCurrentTraceOnce();
@@ -8483,7 +8574,52 @@ export class InteractiveMode {
return;
}
- this.showWarning("Usage: /traces [status|on|off|upload|login]");
+ if (command === "upload-all") {
+ const credential = await getPrimeAgentTraceCredential(this.modelRegistry.authStorage);
+ if (!credential) {
+ this.showError("Trace sharing needs a Prime API key. Run /traces login.");
+ return;
+ }
+ if (this.traceUploadAllAbortController) {
+ this.showWarning("A trace upload is already running. Cancel it before starting another.");
+ return;
+ }
+ const state = await this.agentConnection.getState();
+ const abortController = new AbortController();
+ this.traceUploadAllAbortController = abortController;
+ let result: AgentTraceUploadAllResult;
+ try {
+ result = await this.uploadAllTraces(state.sessionDir, abortController.signal);
+ } finally {
+ if (this.traceUploadAllAbortController === abortController) {
+ this.traceUploadAllAbortController = undefined;
+ }
+ }
+ if (abortController.signal.aborted) {
+ this.showStatus("Trace upload cancelled.");
+ return;
+ }
+ if (result.total === 0) {
+ this.showStatus("No persisted traces were found.");
+ return;
+ }
+ const summary = [
+ `Uploaded ${result.uploaded.toLocaleString()} of ${result.total.toLocaleString()} traces`,
+ result.skipped > 0 ? `${result.skipped.toLocaleString()} skipped` : undefined,
+ result.failed > 0 ? `${result.failed.toLocaleString()} failed` : undefined,
+ `${result.bytesStored.toLocaleString()} bytes stored`,
+ ]
+ .filter((part): part is string => part !== undefined)
+ .join("; ");
+ if (result.failed > 0) {
+ this.showWarning(`${summary}. See ${getAgentTracesLogPath()} for details.`);
+ } else {
+ this.showStatus(`${summary}.`);
+ }
+ return;
+ }
+
+ this.showWarning("Usage: /traces [status|on|off|preview|upload|upload-current|upload-all|login]");
}
private async handleContextCommand(): Promise<void> {
diff --git a/packages/coding-agent/test/agent-traces.test.ts b/packages/coding-agent/test/agent-traces.test.ts
index 72ee37cb7b..1648e2812c 100644
--- a/packages/coding-agent/test/agent-traces.test.ts
+++ b/packages/coding-agent/test/agent-traces.test.ts
@@ -1,10 +1,18 @@
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { AssistantMessage } from "@earendil-works/pi-ai";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { ENV_AGENT_DIR, getAgentTracesLogPath } from "../src/config.js";
-import { flushAgentTraceUpload, installAgentTraceUpload, uploadAgentTraceFile } from "../src/core/agent-traces.js";
+import {
+ findAgentTraceFiles,
+ flushAgentTraceUpload,
+ installAgentTraceUpload,
+ previewAgentTraceFile,
+ uploadAgentTraceFile,
+ uploadAllAgentTraces,
+} from "../src/core/agent-traces.js";
import { AuthStorage } from "../src/core/auth-storage.js";
import { PRIME_AGENT_TRACES_PROVIDER_ID, PRIME_INFERENCE_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
import { SessionManager } from "../src/core/session-manager.js";
@@ -66,6 +74,18 @@ function writeSession(cwd: string, sessionDir: string, id: string, parentSession
return sessionManager;
}
+async function advanceTimersUntil(condition: () => boolean): Promise<void> {
+ for (let step = 0; step < 20 && !condition(); step += 1) {
+ await stat(new URL(import.meta.url));
+ if (!condition() && vi.getTimerCount() > 0) {
+ await vi.advanceTimersToNextTimerAsync();
+ }
+ }
+ if (!condition()) {
+ throw new Error("Timed out advancing fake timers to the expected condition");
+ }
+}
+
describe("agent trace upload", () => {
let tempDir: string;
let originalTraceApiKey: string | undefined;
@@ -89,6 +109,7 @@ describe("agent trace upload", () => {
});
afterEach(() => {
+ vi.restoreAllMocks();
vi.useRealTimers();
if (originalAgentDir === undefined) {
delete process.env[ENV_AGENT_DIR];
@@ -138,6 +159,25 @@ describe("agent trace upload", () => {
expect(calls).toHaveLength(0);
});
+ it("allows an explicit one-shot upload without enabling automatic sharing", async () => {
+ const sessionManager = writeSession(tempDir, join(tempDir, "sessions"), "one-shot-session");
+ const calls: FetchCall[] = [];
+ const result = await uploadAgentTraceFile({
+ sessionFile: sessionManager.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: false } }),
+ requireEnabled: false,
+ baseUrl: "https://api.example.test",
+ fetchFn: createFetchRecorder(calls),
+ reloadConfig: false,
+ });
+
+ expect(result.status).toBe("uploaded");
+ expect(calls).toHaveLength(1);
+ });
+
it("stops before reading the session body when trace sharing is disabled after upload starts", async () => {
const sessionManager = writeSession(tempDir, join(tempDir, "sessions"), "disabled-before-read-session");
const settingsManager = SettingsManager.inMemory({ agentTraces: { enabled: true } });
@@ -442,6 +482,212 @@ describe("agent trace upload", () => {
expect(calls).toHaveLength(1);
});
+ it("uses bounded exponential backoff with jitter for transient failures", async () => {
+ const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0);
+ const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "bounded-retry-session");
+ let attempts = 0;
+ const failingFetch: typeof fetch = async () => {
+ attempts += 1;
+ const error = new TypeError("fetch failed");
+ (error as { cause?: unknown }).cause = { code: "ECONNRESET" };
+ throw error;
+ };
+
+ const result = await uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn: failingFetch,
+ reloadConfig: false,
+ });
+ expect(attempts).toBe(4);
+ expect(result.status).toBe("failed");
+ const retryDelays = timeoutSpy.mock.calls.map((call) => Number(call[1])).filter((delay) => delay < 15_000);
+ expect(retryDelays).toEqual([400, 800, 1_600]);
+ randomSpy.mockRestore();
+ });
+
+ it("retries request timeouts within the retry bound", async () => {
+ vi.useFakeTimers();
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "timeout-retry-session");
+ let markFirstAttemptStarted: () => void = () => {};
+ const firstAttemptStarted = new Promise<void>((resolve) => {
+ markFirstAttemptStarted = resolve;
+ });
+ let attempts = 0;
+ const timeoutFetch: typeof fetch = async (_input, init) => {
+ attempts += 1;
+ if (attempts === 1) {
+ markFirstAttemptStarted();
+ }
+ return await new Promise<Response>((_resolve, reject) => {
+ const signal = init?.signal;
+ signal?.addEventListener("abort", () => reject(signal.reason), { once: true });
+ });
+ };
+
+ const upload = uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn: timeoutFetch,
+ requestTimeoutMs: 100,
+ reloadConfig: false,
+ });
+
+ await firstAttemptStarted;
+ await vi.runAllTimersAsync();
+ const result = await upload;
+ expect(attempts).toBe(4);
+ expect(result).toEqual({ status: "failed", message: "Trace upload timed out after 100ms" });
+ });
+
+ it("retries transient HTTP responses but not permanent HTTP responses", async () => {
+ const randomSpy = vi.spyOn(Math, "random").mockReturnValue(0.5);
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "http-retry-session");
+ let attempts = 0;
+ const fetchFn: typeof fetch = async () => {
+ attempts += 1;
+ if (attempts < 3) {
+ return new Response(JSON.stringify({ detail: "temporarily unavailable" }), { status: 503 });
+ }
+ return new Response(JSON.stringify({ bytes_stored: 42 }), { status: 200 });
+ };
+
+ const result = await uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ });
+ expect(attempts).toBe(3);
+ expect(result.status).toBe("uploaded");
+ randomSpy.mockRestore();
+ });
+
+ it("waits a full platform window before retrying a rate limit without Retry-After", async () => {
+ vi.useFakeTimers();
+ const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "rate-limit-retry-session");
+ let markFirstAttemptStarted: () => void = () => {};
+ const firstAttemptStarted = new Promise<void>((resolve) => {
+ markFirstAttemptStarted = resolve;
+ });
+ let attempts = 0;
+ const fetchFn: typeof fetch = async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ markFirstAttemptStarted();
+ return new Response(JSON.stringify({ detail: "Too Many Requests" }), { status: 429 });
+ }
+ return new Response(JSON.stringify({ bytes_stored: 42 }), { status: 200 });
+ };
+
+ const upload = uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ });
+
+ await firstAttemptStarted;
+ await vi.runAllTimersAsync();
+ const result = await upload;
+ expect(attempts).toBe(2);
+ expect(result.status).toBe("uploaded");
+ expect(timeoutSpy.mock.calls.map((call) => Number(call[1]))).toContain(60_000);
+ });
+
+ it.each([429, 503])("honors Retry-After when retrying HTTP %i", async (status) => {
+ vi.useFakeTimers();
+ const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ const session = writeSession(tempDir, join(tempDir, "sessions"), `retry-after-session-${status}`);
+ let markFirstAttemptStarted: () => void = () => {};
+ const firstAttemptStarted = new Promise<void>((resolve) => {
+ markFirstAttemptStarted = resolve;
+ });
+ let attempts = 0;
+ const fetchFn: typeof fetch = async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ markFirstAttemptStarted();
+ return new Response(null, { status, headers: { "retry-after": "17" } });
+ }
+ return new Response(JSON.stringify({ bytes_stored: 42 }), { status: 200 });
+ };
+
+ const upload = uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ });
+
+ await firstAttemptStarted;
+ await vi.runAllTimersAsync();
+ const result = await upload;
+ expect(attempts).toBe(2);
+ expect(result.status).toBe("uploaded");
+ expect(timeoutSpy.mock.calls.map((call) => Number(call[1]))).toContain(17_000);
+ });
+
+ it("caps Retry-After at the platform rate-limit window", async () => {
+ vi.useFakeTimers();
+ const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "bounded-retry-after-session");
+ let markFirstAttemptStarted: () => void = () => {};
+ const firstAttemptStarted = new Promise<void>((resolve) => {
+ markFirstAttemptStarted = resolve;
+ });
+ let attempts = 0;
+ const fetchFn: typeof fetch = async () => {
+ attempts += 1;
+ if (attempts === 1) {
+ markFirstAttemptStarted();
+ return new Response(null, { status: 429, headers: { "retry-after": "3600" } });
+ }
+ return new Response(JSON.stringify({ bytes_stored: 42 }), { status: 200 });
+ };
+
+ const upload = uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ });
+
+ await firstAttemptStarted;
+ await vi.runAllTimersAsync();
+ const result = await upload;
+ expect(attempts).toBe(2);
+ expect(result.status).toBe("uploaded");
+ expect(timeoutSpy.mock.calls.map((call) => Number(call[1]))).toContain(60_000);
+ expect(timeoutSpy.mock.calls.map((call) => Number(call[1]))).not.toContain(3_600_000);
+ });
+
it("surfaces the cancellation reason when aborted during the retry backoff", async () => {
const session = writeSession(tempDir, join(tempDir, "sessions"), "aborted-retry-session");
const controller = new AbortController();
@@ -474,6 +720,46 @@ describe("agent trace upload", () => {
}
});
+ it("does not back off when an HTTP response cleanup aborts the upload", async () => {
+ vi.useFakeTimers();
+ const timeoutSpy = vi.spyOn(globalThis, "setTimeout");
+ const session = writeSession(tempDir, join(tempDir, "sessions"), "aborted-http-retry-session");
+ const controller = new AbortController();
+ const abortReason = new Error("upload cancelled during cleanup");
+ let attempts = 0;
+ const fetchFn: typeof fetch = async () => {
+ attempts += 1;
+ return {
+ status: 503,
+ headers: new Headers(),
+ body: {
+ cancel: async () => {
+ controller.abort(abortReason);
+ },
+ },
+ } as unknown as Response;
+ };
+
+ const upload = uploadAgentTraceFile({
+ sessionFile: session.getSessionFile(),
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: true } }),
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ signal: controller.signal,
+ reloadConfig: false,
+ });
+
+ await vi.runAllTimersAsync();
+ const result = await upload;
+ expect(attempts).toBe(1);
+ expect(result).toEqual({ status: "failed", message: "upload cancelled during cleanup" });
+ const retryDelays = timeoutSpy.mock.calls.map((call) => Number(call[1])).filter((delay) => delay < 15_000);
+ expect(retryDelays).toEqual([]);
+ });
+
it("does not retry a permanent DNS failure", async () => {
const session = writeSession(tempDir, join(tempDir, "sessions"), "dns-failure-session");
let attempts = 0;
@@ -531,6 +817,217 @@ describe("agent trace upload", () => {
}
});
+ it("previews the current trace without requiring sharing or credentials", async () => {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ mkdirSync(cwd, { recursive: true });
+ const parent = writeSession(cwd, sessionDir, "preview-parent");
+ const child = writeSession(cwd, sessionDir, "preview-child", parent.getSessionFile());
+
+ const result = await previewAgentTraceFile({
+ sessionFile: child.getSessionFile(),
+ baseUrl: "https://api.example.test",
+ maxContentChars: 256,
+ });
+
+ expect(result.status).toBe("ready");
+ if (result.status === "ready") {
+ expect(result).toMatchObject({
+ sessionId: "preview-child",
+ traceId: "preview-parent",
+ parentSessionId: "preview-parent",
+ cwd,
+ uploadable: true,
+ endpoint: "https://api.example.test/api/v1/agent-traces/sessions/preview-child",
+ truncated: true,
+ });
+ expect(result.contentPreview).toContain("middle of trace omitted");
+ expect(result.contentPreview).toContain("preview-child");
+ }
+ });
+
+ it("discovers and uploads saved parent and subagent traces", async () => {
+ const cwd = join(tempDir, "project");
+ const sessionDir = join(tempDir, "sessions");
+ mkdirSync(cwd, { recursive: true });
+ const parent = writeSession(cwd, sessionDir, "all-parent");
+ const childDir = join(tempDir, "session-artifacts", "all-parent", "sub-12345678");
+ const child = writeSession(cwd, childDir, "all-child", parent.getSessionFile());
+ const grandchildDir = join(childDir, "sub-87654321");
+ const grandchild = writeSession(cwd, grandchildDir, "all-grandchild", child.getSessionFile());
+ writeFileSync(join(childDir, "not-a-session.jsonl"), '{"type":"diagnostic"}\n');
+
+ const discovered = await findAgentTraceFiles(sessionDir);
+ expect(discovered).toEqual([child.getSessionFile(), grandchild.getSessionFile(), parent.getSessionFile()].sort());
+
+ vi.useFakeTimers();
+ const calls: FetchCall[] = [];
+ let resolveFirstCompletion: () => void = () => {};
+ const firstCompletion = new Promise<void>((resolve) => {
+ resolveFirstCompletion = resolve;
+ });
+ const progress: Array<{ completed: number; total: number }> = [];
+ const upload = uploadAllAgentTraces({
+ sessionDir,
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: false } }),
+ requireEnabled: false,
+ baseUrl: "https://api.example.test",
+ fetchFn: createFetchRecorder(calls),
+ reloadConfig: false,
+ concurrency: 0.5,
+ onProgress: ({ completed, total }) => {
+ progress.push({ completed, total });
+ if (completed === 1) {
+ resolveFirstCompletion();
+ }
+ },
+ });
+ await firstCompletion;
+ await advanceTimersUntil(() => calls.length === 3);
+ const result = await upload;
+
+ expect(result).toMatchObject({ total: 3, uploaded: 3, failed: 0, skipped: 0, bytesStored: 369 });
+ expect(calls.map((call) => call.url).sort()).toEqual(
+ [
+ "https://api.example.test/api/v1/agent-traces/sessions/all-child",
+ "https://api.example.test/api/v1/agent-traces/sessions/all-grandchild",
+ "https://api.example.test/api/v1/agent-traces/sessions/all-parent",
+ ].sort(),
+ );
+ const grandchildCall = calls.find((call) => call.url.endsWith("/all-grandchild"));
+ const grandchildHeaders = new Headers(grandchildCall?.init.headers);
+ expect(grandchildHeaders.get("x-trace-id")).toBe("all-parent");
+ expect(grandchildHeaders.get("x-parent-session")).toBe("all-child");
+ expect(progress[0]).toEqual({ completed: 0, total: 3 });
+ expect(progress.at(-1)).toEqual({ completed: 3, total: 3 });
+ });
+
+ it("paces batch request starts within the platform rate limit", async () => {
+ const sessionDir = join(tempDir, "sessions");
+ for (let index = 0; index < 6; index += 1) {
+ writeSession(tempDir, sessionDir, `rate-limited-all-${index}`);
+ }
+
+ vi.useFakeTimers();
+ let markFirstRequestStarted: () => void = () => {};
+ const firstRequestStarted = new Promise<void>((resolve) => {
+ markFirstRequestStarted = resolve;
+ });
+ const requestStarts: number[] = [];
+ const fetchFn: typeof fetch = async () => {
+ requestStarts.push(Date.now());
+ if (requestStarts.length === 1) {
+ markFirstRequestStarted();
+ }
+ return new Response(JSON.stringify({ bytes_stored: 1 }), { status: 200 });
+ };
+
+ const upload = uploadAllAgentTraces({
+ sessionDir,
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: false } }),
+ requireEnabled: false,
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ });
+
+ await firstRequestStarted;
+ await advanceTimersUntil(() => requestStarts.length === 6);
+ const result = await upload;
+ expect(result).toMatchObject({ total: 6, uploaded: 6, failed: 0, skipped: 0 });
+ expect(requestStarts).toHaveLength(6);
+ for (let index = 1; index < requestStarts.length; index += 1) {
+ expect(requestStarts[index]! - requestStarts[index - 1]!).toBeGreaterThanOrEqual(12_000);
+ }
+ expect(requestStarts[5]! - requestStarts[0]!).toBeGreaterThanOrEqual(60_000);
+ });
+
+ it("stops scheduling batch uploads after cancellation", async () => {
+ const sessionDir = join(tempDir, "sessions");
+ writeSession(tempDir, sessionDir, "abort-all-a");
+ writeSession(tempDir, sessionDir, "abort-all-b");
+ writeSession(tempDir, sessionDir, "abort-all-c");
+ const controller = new AbortController();
+ const calls: FetchCall[] = [];
+
+ const result = await uploadAllAgentTraces({
+ sessionDir,
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: false } }),
+ requireEnabled: false,
+ baseUrl: "https://api.example.test",
+ fetchFn: createFetchRecorder(calls),
+ reloadConfig: false,
+ concurrency: 1,
+ signal: controller.signal,
+ onProgress: ({ completed }) => {
+ if (completed === 1) {
+ controller.abort(new Error("cancel batch"));
+ }
+ },
+ });
+
+ expect(calls).toHaveLength(1);
+ expect(result).toMatchObject({ total: 3, uploaded: 1, failed: 0, skipped: 2 });
+ expect(result.results).toHaveLength(1);
+ });
+
+ it("counts in-flight batch cancellations as skipped", async () => {
+ const sessionDir = join(tempDir, "sessions");
+ writeSession(tempDir, sessionDir, "abort-in-flight-a");
+ writeSession(tempDir, sessionDir, "abort-in-flight-b");
+ writeSession(tempDir, sessionDir, "abort-in-flight-c");
+ const controller = new AbortController();
+ const abortReason = new Error("cancel in-flight batch");
+ vi.useFakeTimers();
+ let markFirstRequestStarted: () => void = () => {};
+ const firstRequestStarted = new Promise<void>((resolve) => {
+ markFirstRequestStarted = resolve;
+ });
+ let attempts = 0;
+ const fetchFn: typeof fetch = async (_input, init) => {
+ attempts += 1;
+ if (attempts === 1) {
+ markFirstRequestStarted();
+ }
+ return await new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
+ if (attempts === 2) {
+ queueMicrotask(() => controller.abort(abortReason));
+ }
+ });
+ };
+
+ const upload = uploadAllAgentTraces({
+ sessionDir,
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ settingsManager: SettingsManager.inMemory({ agentTraces: { enabled: false } }),
+ requireEnabled: false,
+ baseUrl: "https://api.example.test",
+ fetchFn,
+ reloadConfig: false,
+ concurrency: 2,
+ signal: controller.signal,
+ });
+ await firstRequestStarted;
+ await advanceTimersUntil(() => attempts === 2);
+ const result = await upload;
+
+ expect(attempts).toBe(2);
+ expect(result).toMatchObject({ total: 3, uploaded: 0, failed: 0, skipped: 3 });
+ expect(result.results).toHaveLength(0);
+ });
+
it("prefers the prime-inference credential over the prime-cli config key", async () => {
const session = writeSession(tempDir, join(tempDir, "sessions"), "credential-order-session");
const calls: FetchCall[] = [];
diff --git a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
index 89ee712303..e22ca17a36 100644
--- a/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
+++ b/packages/coding-agent/test/interactive-mode-ctrl-c.test.ts
@@ -16,6 +16,7 @@ type FakeInteractiveMode = {
escapeRepeatAction: "tree" | "clear" | undefined;
escapeRepeatExpiresAt: number;
escapeRepeatTimer: ReturnType<typeof setTimeout> | undefined;
+ traceUploadAllAbortController: AbortController | undefined;
isShuttingDown: boolean;
editor: FakeEditor;
connectionState: {
@@ -85,6 +86,7 @@ function createInteractiveFake(options: {
escapeRepeatAction: undefined,
escapeRepeatExpiresAt: 0,
escapeRepeatTimer: undefined,
+ traceUploadAllAbortController: undefined,
isShuttingDown: false,
editor,
connectionState: {
@@ -150,6 +152,21 @@ describe("InteractiveMode interrupt shortcuts", () => {
expect(mode.shutdown).not.toHaveBeenCalled();
});
+ it.each([
+ ["Ctrl+C", "handleCtrlC"],
+ ["Escape", "handleEscape"],
+ ] as const)("cancels an upload-all operation on %s", (_label, handlerName) => {
+ const mode = createInteractiveFake({});
+ const controller = new AbortController();
+ mode.traceUploadAllAbortController = controller;
+
+ Reflect.get(InteractiveMode.prototype, handlerName).call(mode);
+
+ expect(controller.signal.aborted).toBe(true);
+ expect(controller.signal.reason).toEqual(new Error("Trace upload cancelled"));
+ expect(mode.shutdown).not.toHaveBeenCalled();
+ });
+
it("restores queued messages through the atomic abort-and-clear path", async () => {
const mode = createInteractiveFake({ editorText: "draft" });
mode.agentConnection.abortAndClearQueue.mockResolvedValue({
diff --git a/packages/coding-agent/test/interactive-mode-traces-command.test.ts b/packages/coding-agent/test/interactive-mode-traces-command.test.ts
new file mode 100644
index 0000000000..5c5a5c70ee
--- /dev/null
+++ b/packages/coding-agent/test/interactive-mode-traces-command.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it, vi } from "vitest";
+import type { AgentTraceUploadAllResult, AgentTraceUploadResult } from "../src/core/agent-traces.js";
+import { AuthStorage } from "../src/core/auth-storage.js";
+import { PRIME_AGENT_TRACES_PROVIDER_ID } from "../src/core/prime-inference-auth.js";
+import { InteractiveMode } from "../src/modes/interactive/interactive-mode.js";
+
+interface TracesCommandContext {
+ traceUploadAllAbortController?: AbortController;
+ agentConnection: { getState: () => Promise<{ sessionDir?: string }> };
+ settingsManager: {
+ getAgentTracesEnabled: () => boolean;
+ setAgentTracesEnabled: (enabled: boolean) => void;
+ flush: () => Promise<void>;
+ };
+ modelRegistry: { authStorage: AuthStorage };
+ previewCurrentTrace: () => Promise<void>;
+ uploadCurrentTraceOnce: () => Promise<AgentTraceUploadResult>;
+ uploadAllTraces: (sessionDir?: string, signal?: AbortSignal) => Promise<AgentTraceUploadAllResult>;
+ formatTraceUploadResult: (result: AgentTraceUploadResult) => string;
+ showStatus: (message: string) => void;
+ showWarning: (message: string) => void;
+ showError: (message: string) => void;
+}
+
+interface TracesCommandPrototype {
+ handleTracesCommand(this: TracesCommandContext, text: string): Promise<void>;
+}
+
+const prototype = InteractiveMode.prototype as unknown as TracesCommandPrototype;
+
+function makeContext(enabled = true): TracesCommandContext {
+ return {
+ agentConnection: { getState: vi.fn(async () => ({ sessionDir: "/custom/sessions" })) },
+ settingsManager: {
+ getAgentTracesEnabled: () => enabled,
+ setAgentTracesEnabled: vi.fn(),
+ flush: vi.fn(async () => {}),
+ },
+ modelRegistry: {
+ authStorage: AuthStorage.inMemory({
+ [PRIME_AGENT_TRACES_PROVIDER_ID]: { type: "api_key", key: "trace-key" },
+ }),
+ },
+ previewCurrentTrace: vi.fn(async () => {}),
+ uploadCurrentTraceOnce: vi.fn(
+ async (): Promise<AgentTraceUploadResult> => ({
+ status: "uploaded",
+ sessionId: "current",
+ traceId: "current",
+ bytesStored: 12,
+ }),
+ ),
+ uploadAllTraces: vi.fn(
+ async (): Promise<AgentTraceUploadAllResult> => ({
+ total: 2,
+ uploaded: 2,
+ failed: 0,
+ skipped: 0,
+ bytesStored: 24,
+ results: [],
+ }),
+ ),
+ formatTraceUploadResult: vi.fn(() => "Trace uploaded (12 bytes)."),
+ showStatus: vi.fn(),
+ showWarning: vi.fn(),
+ showError: vi.fn(),
+ };
+}
+
+describe("InteractiveMode /traces", () => {
+ it("previews without enabling trace sharing", async () => {
+ const context = makeContext(false);
+
+ await prototype.handleTracesCommand.call(context, "/traces preview");
+
+ expect(context.previewCurrentTrace).toHaveBeenCalledOnce();
+ expect(context.uploadCurrentTraceOnce).not.toHaveBeenCalled();
+ expect(context.uploadAllTraces).not.toHaveBeenCalled();
+ });
+
+ it.each(["/traces upload", "/traces upload-current"])("uploads only the current trace for %s", async (command) => {
+ const context = makeContext(false);
+
+ await prototype.handleTracesCommand.call(context, command);
+
+ expect(context.uploadCurrentTraceOnce).toHaveBeenCalledOnce();
+ expect(context.uploadAllTraces).not.toHaveBeenCalled();
+ expect(context.showStatus).toHaveBeenCalledWith("Trace uploaded (12 bytes).");
+ });
+
+ it.each(["no_session_file", "empty_session"] as const)(
+ "keeps future upload guidance when enabling from %s",
+ async (status) => {
+ const context = makeContext(false);
+ vi.mocked(context.uploadCurrentTraceOnce).mockResolvedValue({ status });
+
+ await prototype.handleTracesCommand.call(context, "/traces on");
+
+ expect(context.settingsManager.setAgentTracesEnabled).toHaveBeenCalledWith(true);
+ expect(context.showStatus).toHaveBeenCalledWith(
+ "Trace sharing enabled. Current session will upload after the first assistant response.",
+ );
+ },
+ );
+
+ it("backfills all discovered traces only for upload-all", async () => {
+ const context = makeContext(false);
+
+ await prototype.handleTracesCommand.call(context, "/traces upload-all");
+
+ expect(context.uploadAllTraces).toHaveBeenCalledWith("/custom/sessions", expect.any(AbortSignal));
+ expect(context.uploadCurrentTraceOnce).not.toHaveBeenCalled();
+ expect(context.showStatus).toHaveBeenCalledWith("Uploaded 2 of 2 traces; 24 bytes stored.");
+ });
+
+ it("reports a cancelled upload-all without a success summary", async () => {
+ const context = makeContext(false);
+ vi.mocked(context.uploadAllTraces).mockImplementation(async (_sessionDir, signal) => {
+ return await new Promise<AgentTraceUploadAllResult>((resolve) => {
+ signal?.addEventListener(
+ "abort",
+ () =>
+ resolve({
+ total: 2,
+ uploaded: 0,
+ failed: 0,
+ skipped: 2,
+ bytesStored: 0,
+ results: [],
+ }),
+ { once: true },
+ );
+ });
+ });
+
+ const command = prototype.handleTracesCommand.call(context, "/traces upload-all");
+ await vi.waitFor(() => expect(context.traceUploadAllAbortController).toBeDefined());
+ context.traceUploadAllAbortController?.abort();
+ await command;
+
+ expect(context.showStatus).toHaveBeenCalledWith("Trace upload cancelled.");
+ expect(context.showStatus).not.toHaveBeenCalledWith(expect.stringContaining("Uploaded 0 of 2"));
+ expect(context.traceUploadAllAbortController).toBeUndefined();
+ });
+});
diff --git a/packages/coding-agent/test/slash-commands.test.ts b/packages/coding-agent/test/slash-commands.test.ts
index 8a2e34224d..c15e14c5dd 100644
--- a/packages/coding-agent/test/slash-commands.test.ts
+++ b/packages/coding-agent/test/slash-commands.test.ts
@@ -51,6 +51,13 @@ describe("built-in slash commands", () => {
});
});
+ test("exposes trace preview and backfill syntax", () => {
+ expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "traces")).toMatchObject({
+ description: "Preview, upload, or configure Prime Agent traces",
+ argumentHint: "[status|on|off|preview|upload|upload-current|upload-all|login]",
+ });
+ });
+
test("marks argument commands as taking a free-form argument", () => {
expect(BUILTIN_SLASH_COMMANDS.find((command) => command.name === "goal")).toMatchObject({
takesArgument: true,