A local-first multi-agent app development platform, built on PenguinHarness
feat(traces): 被压缩过的长会话可以整套迁到另一台 Adelie
lmliheng5b5e5426d35e
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex c0bc2ff2..77585dd5 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3700,17 +3700,48 @@ export interface AgentTracesResponse {}export interface TraceImportRequest {- /** Base64 of the Trace file content (JSON Lines; the first record must be `session_meta`). */+ /**+ * Base64 of the uploaded content, in either of the two shapes the import accepts: a single+ * Trace file (JSON Lines; the first record must be `session_meta`) or a whole-Session+ * migration bundle (see `TraceBundle`).+ */dataBase64: string;}+/** One Trace shard inside a migration bundle, carrying that shard's file content verbatim. */+export interface TraceBundleShard {+ /** Trace file index, 1-based. A bundle's shards are contiguous from 1 — the indices the shards land under here. */+ index: number;+ /** The shard's JSON Lines content, byte-for-byte what the exporting install has on disk. */+ content: string;+}++/**+ * A whole Session's Trace as one file — what makes a Session with several compaction shards+ * migratable: a single file holds only one shard, so an export → import round-trip of a long+ * Session used to carry nothing but its first context.+ *+ * `format` is what tells a bundle apart from a single Trace file when one is uploaded: a Trace+ * file is JSON Lines, a bundle is one JSON object.+ */+export interface TraceBundle {+ format: "adelie-trace-bundle";+ version: 1;+ /** The Session every shard belongs to; each shard's `session_meta` must agree with it. */+ sessionId: string;+ /** Every shard, in index order. */+ shards: TraceBundleShard[];+}+export interface TraceImportResponse {- /** Session id taken from the imported file's `session_meta`. */+ /** Session id taken from the imported file's (or bundle's) `session_meta`. */sessionId: string;- /** Allocated file index: always 1 — an import creates a new Session (a duplicate session id is rejected with 409 `trace_session_exists`). */+ /** Allocated first file index: always 1 — an import creates a new Session (a duplicate session id is rejected with 409 `trace_session_exists`). */index: number;- /** Date directory the file landed in (local yyyy-mm-dd from the first record's timestamp, matching the Trace Writer's convention). */+ /** Date directory the first shard landed in (local yyyy-mm-dd from that shard's first-record timestamp, matching the Trace Writer's convention). */date: string;+ /** Shards written: 1 for a single-file import, N for a bundle (they land as indices 1..N of one Session). */+ shards: number;}// ---------------------------------------------------------------------------diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.tsindex a7a90038..2cc43ab8 100644--- a/packages/server/src/http/routes/agent-traces.ts+++ b/packages/server/src/http/routes/agent-traces.ts@@ -17,10 +17,13 @@* (projectId, agentId, sessionId), without depending on the sessions table for* tracking — any entry visible in the directory tree (subagent child Sessions,* CLI-created Sessions) can be opened and read; access is enforced by requireProjectAccess.- * - POST /api/projects/:p/agents/:a/traces/import — uploads a Trace JSONL file (owner- * only, mirroring the Agent snapshot import); the file names itself via its- * session_meta and always becomes index 001 of a new Session — a session id the- * Agent already has is rejected with 409 trace_session_exists.+ * - GET /api/projects/:p/agents/:a/traces/:sessionId/export — the whole Session as one+ * migration bundle (every shard), for import on another install.+ * - POST /api/projects/:p/agents/:a/traces/import — uploads a Trace JSONL file or a+ * whole-Session bundle (owner only, mirroring the Agent snapshot import); the content+ * names itself via its session_meta and always becomes a new Session (indices 1..N for+ * a bundle) — a session id the Agent already has is rejected with 409+ * trace_session_exists.*/import { Hono } from "hono";import type { AppEnv } from "../../auth/middleware.js";@@ -48,6 +51,18 @@ export interface AgentTracesRouteDeps {/** Import file size cap: aligned with the snapshot import (stays within the 20MB body limit after base64). */const MAX_TRACE_BYTES = 14 * 1024 * 1024;+/**+ * Import cap for a whole-Session **bundle** — every shard of one Session in a single upload.+ * Larger than the single-file cap by design: a Session that was compacted is several files, and+ * the point of a bundle is to carry them together. It is still a ceiling, and a loud one: a+ * Session past it is refused with a message naming the limit rather than truncated — migrating+ * such a Session is simply not covered yet (a shard cannot be imported on its own either, by the+ * rule that only ever creates a Session).+ */+const MAX_TRACE_BUNDLE_BYTES = 48 * 1024 * 1024;+/** Base64 of a capped upload inflates by 4/3, plus the JSON envelope's quotes. */+const base64Cap = (bytes: number): number => Math.ceil(bytes * (4 / 3)) + 1024;+/** Accepted `category` query values of the paginated listing (SessionCategory, spelled out for validation — same as the sessions list route). */const SESSION_CATEGORIES: readonly SessionCategory[] = ["active", "background", "archived"];@@ -79,6 +94,25 @@ export function agentTracesRoutes(deps: AgentTracesRouteDeps): Hono<AppEnv> {);});+ // Whole-Session export (any member, like the per-file download): every shard of one Session+ // in a single file, so a long Session can be moved to another install in one piece. Registered+ // BEFORE the `/:sessionId/:index` routes — otherwise "export" would be read as an index.+ app.get("/:sessionId/export", async (c) => {+ const projectId = requireValidId(c, "projectId");+ const agentId = requireValidId(c, "agentId");+ const sessionId = requireValidId(c, "sessionId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);+ const bundle = await deps.traceService.exportSessionBundle(projectId, agentId, sessionId);+ const fileName = `${sessionId}.trace-bundle.json`;+ return new Response(JSON.stringify(bundle), {+ headers: {+ "Content-Type": "application/json",+ "Content-Disposition": `attachment; filename*=UTF-8''${encodeURIComponent(fileName)}`,+ "X-Content-Type-Options": "nosniff",+ },+ });+ });+app.get("/:sessionId/:index", async (c) => {const projectId = requireValidId(c, "projectId");const agentId = requireValidId(c, "agentId");@@ -128,11 +162,22 @@ export function agentTracesRoutes(deps: AgentTracesRouteDeps): Hono<AppEnv> {deps.access.requireProjectOwner(c.var.user.userId, projectId);await deps.agentConfigService.requireExists(projectId, agentId);const body = await readJson(c);- const dataBase64 = requireString(body, "dataBase64", { minLen: 1, maxLen: 20 * 1024 * 1024 });+ const dataBase64 = requireString(body, "dataBase64", {+ minLen: 1,+ maxLen: base64Cap(MAX_TRACE_BUNDLE_BYTES),+ });const bytes = Buffer.from(dataBase64, "base64");if (bytes.byteLength === 0) throw badRequest("Import file is empty.");- if (bytes.byteLength > MAX_TRACE_BYTES) {- throw badRequest("Import file exceeds the 14MB limit.");+ // One upload, two caps: a whole-Session bundle (the larger ceiling) is a single JSON object —+ // a Trace file is JSON Lines, whose first character is also `{` but whose only possible+ // one-line content is a bare record with no bundle marker. The shape decides the cap, and the+ // service decides the shape; a single Trace file keeps the 14MB ceiling it always had.+ const isBundle = bytes.subarray(0, 256).toString("utf8").trimStart().startsWith("{");+ const cap = isBundle ? MAX_TRACE_BUNDLE_BYTES : MAX_TRACE_BYTES;+ if (bytes.byteLength > cap) {+ throw badRequest(+ isBundle ? "Import bundle exceeds the 48MB limit." : "Import file exceeds the 14MB limit.",+ );}const res: TraceImportResponse = await deps.traceService.importTraceFile(projectId,diff --git a/packages/server/src/mechanisms/traces.ts b/packages/server/src/mechanisms/traces.tsindex 0efa8d2f..d2127d5a 100644--- a/packages/server/src/mechanisms/traces.ts+++ b/packages/server/src/mechanisms/traces.ts@@ -8,6 +8,7 @@ import type {HistoryMessage,SessionContextParts,TraceAnalysisResponse,+ TraceBundle,TraceEventsResponse,TraceFileInfo,TraceImportResponse,@@ -188,6 +189,11 @@ export abstract class Traces {sessionId: string,index: number,): Promise<Buffer<ArrayBufferLike>>;+ abstract exportSessionBundle(+ projectId: string,+ agentId: string,+ sessionId: string,+ ): Promise<TraceBundle>;abstract importTraceFile(projectId: string,agentId: string,diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.tsindex 404b477a..7b5313b0 100644--- a/packages/server/src/services/trace-service.ts+++ b/packages/server/src/services/trace-service.ts@@ -38,6 +38,8 @@ import type {SessionCategoryCounts,SessionContextParts,HistoryMessage,+ TraceBundle,+ TraceBundleShard,TracePosition,ToolCallSpan,TraceAnalysisResponse,@@ -93,6 +95,117 @@ const TRACE_FILE_RE = /^(.+)_(\d{3})\.jsonl$/;*/const IMPORT_SESSION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;+/**+ * Shard-count sanity bound for a migration bundle. A shard is one model context — a Session+ * rotates on every compaction — so a real Session stays far below this; the bound exists so a+ * hand-made upload cannot ask for an unbounded number of files in one request.+ */+const MAX_TRACE_BUNDLE_SHARDS = 200;++/** One uploaded shard, validated (see `parseTraceShard`). */+interface ParsedTraceShard {+ /** The shard's records, parsed strictly; the import path is the one place a malformed file is an error rather than a line to skip. */+ records: OmniMessage[];+ /** The session id its leading `session_meta` declares. */+ sessionId: string;+ /** Date directory the shard lands in: the local date of its first record (core Trace Writer's convention). */+ date: string;+}++/**+ * Validates one uploaded shard's content. `what` names it in the error — "The file" for a+ * single-file import, "Shard 3 of 7" inside a bundle — so a rejected upload says which part of+ * it was wrong.+ *+ * Strict parse on purpose: the read paths skip a malformed middle line (torn-tail recovery),+ * but a file the user hands over must be reported, not silently shortened. The session id and+ * the date are taken from the leading `session_meta` — the first record, always, because the+ * Trace Writer opens every shard with the current context's meta.+ */+function parseTraceShard(content: string, what: string): ParsedTraceShard {+ const invalid = (message: string) => new HttpError(400, "invalid_trace", message);+ let records: OmniMessage[];+ try {+ records = parseTraceLines(content, { onMalformed: "throw" });+ } catch {+ throw invalid(`${what} is not valid Trace JSONL.`);+ }+ if (records.length === 0) throw invalid(`${what} contains no Trace records.`);+ const first = records[0]!;+ if (!isSessionMeta(first)) throw invalid(`The first record of ${what} must be session_meta.`);+ // The payload type declares session_id: string, but the value came from user-supplied JSON —+ // re-check the runtime shape before it becomes part of a filename.+ const sessionId: unknown = (first.payload as { session_id?: unknown }).session_id;+ if (typeof sessionId !== "string" || !IMPORT_SESSION_ID_RE.test(sessionId)) {+ throw invalid(`${what} carries a missing or invalid session_id.`);+ }+ const ts = Date.parse(first.timestamp);+ const date = formatLocalDate(Number.isNaN(ts) ? new Date() : new Date(ts));+ return { records, sessionId, date };+}++/**+ * Recognizes an uploaded migration bundle, or returns null for anything that is not one.+ *+ * A single Trace file is JSON Lines: its whole-content JSON parse either fails (more than one+ * line) or yields a bare record with no `format` marker. Both fall through to the single-shard+ * path, which reports what is actually wrong with the file — so the detection never has to+ * explain itself.+ */+function parseTraceBundle(content: string): TraceBundle | null {+ const trimmed = content.trim();+ if (!trimmed.startsWith("{")) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(trimmed);+ } catch {+ return null;+ }+ if (typeof parsed !== "object" || parsed === null) return null;+ const envelope = parsed as {+ format?: unknown;+ version?: unknown;+ sessionId?: unknown;+ shards?: unknown;+ };+ if (envelope.format !== "adelie-trace-bundle") return null;+ const invalid = (message: string) => new HttpError(400, "invalid_trace", message);+ if (envelope.version !== 1) {+ throw invalid(`Unsupported Trace bundle version ${String(envelope.version)}.`);+ }+ const sessionId: unknown = envelope.sessionId;+ if (typeof sessionId !== "string" || !IMPORT_SESSION_ID_RE.test(sessionId)) {+ throw invalid("The bundle carries a missing or invalid sessionId.");+ }+ const raw = envelope.shards;+ if (!Array.isArray(raw) || raw.length === 0) throw invalid("The bundle carries no shards.");+ if (raw.length > MAX_TRACE_BUNDLE_SHARDS) {+ throw invalid(`The bundle carries more than ${MAX_TRACE_BUNDLE_SHARDS} shards.`);+ }+ const shards: TraceBundleShard[] = [];+ for (const entry of raw as unknown[]) {+ const shard = entry as { index?: unknown; content?: unknown };+ if (+ typeof shard !== "object" ||+ shard === null ||+ !Number.isInteger(shard.index) ||+ (shard.index as number) < 1 ||+ typeof shard.content !== "string"+ ) {+ throw invalid("The bundle carries a malformed shard entry.");+ }+ // Contiguity from 1 is what makes the landed filenames a copy of the original Session+ // rather than a renumbering: a gap would silently reorder a transcript.+ if (shard.index !== shards.length + 1) {+ throw invalid(+ `The bundle's shards must run 1..N in order; expected index ${shards.length + 1}, got ${String(shard.index)}.`,+ );+ }+ shards.push({ index: shard.index as number, content: shard.content });+ }+ return { format: "adelie-trace-bundle", version: 1, sessionId, shards };+}+/*** A windowed history page stops adding units once its serialized size (UTF-8, images by* reference) would pass this, but never holds fewer than one unit: the unit count alone does@@ -1783,85 +1896,198 @@ export class TraceService implements Traces {}/**- * Imports an uploaded Trace file (raw JSONL content). Validates the content itself —- * parseable JSONL whose first record is a `session_meta` carrying a filename-safe- * `session_id` (400 invalid_trace otherwise) — then writes it under the Agent's traces- * directory as a **new Session**: a session id the Agent already has is rejected with- * 409 `trace_session_exists` (splicing a further index into an existing Session would- * corrupt its concatenated transcript, silently become its resume point, and could- * collide with a live Writer's rotation), so the imported file is always index 1. The- * date dir comes from the first record's timestamp (falling back to now), formatted as- * a **local** date — the same convention as core's Trace Writer — so an export →- * import round-trip lands in the same date dir on non-UTC servers.+ * Exports a whole Session as a migration bundle (see `TraceBundle`): every shard's content+ * verbatim, in index order, for `importTraceFile` here or on another install to land as one+ * Session. Reads the same files the per-shard download serves, so each shard in a bundle is+ * byte-identical to what exporting that file on its own would give.+ *+ * This is the export side of the migration story: a Session that was compacted lives in+ * several files, and no single file carries more than its own context, so a bundle is what+ * lets the whole conversation travel.+ */+ async exportSessionBundle(+ projectId: string,+ agentId: string,+ sessionId: string,+ ): Promise<TraceBundle> {+ const files = await this.locateAll(projectId, agentId, sessionId);+ if (files.length === 0) {+ throw new HttpError(404, "trace_not_found", `This Session has no Trace files.`);+ }+ const shards: TraceBundleShard[] = [];+ for (const file of files) {+ const raw = await fs.readFile(file.path);+ shards.push({ index: file.index, content: raw.toString("utf8") });+ }+ return { format: "adelie-trace-bundle", version: 1, sessionId, shards };+ }++ /**+ * Imports an uploaded Trace file (raw content). Two shapes are accepted, one gate:+ *+ * - a **single Trace file** — JSON Lines whose first record is a `session_meta` carrying a+ * filename-safe `session_id` (400 invalid_trace otherwise) — lands as index 1 of a new+ * Session;+ * - a **migration bundle** (`exportSessionBundle`'s output) — all of one Session's shards —+ * lands as indices 1..N of ONE Session.+ *+ * A session id that exists ANYWHERE in the install is rejected with 409+ * `trace_session_exists`: splicing a further index into an existing Session would corrupt its+ * concatenated transcript, silently become its resume point, and could collide with a live+ * Writer's rotation. That rule is exactly why a long Session needs the bundle — its later+ * shards could never be imported one by one — and why a bundle is validated in full BEFORE+ * anything is written: a rejected bundle leaves the install as it was, never a Session whose+ * transcript stops in the middle of a context.+ *+ * Each shard's date dir comes from that shard's first-record timestamp (falling back to now),+ * formatted as a **local** date — the same convention as core's Trace Writer — so an export →+ * import round-trip lands in the same date dirs on non-UTC servers.*/async importTraceFile(projectId: string,agentId: string,content: string,): Promise<TraceImportResponse> {- const invalid = (message: string) => new HttpError(400, "invalid_trace", message);- let records: OmniMessage[];- try {- // Strict parse: import is the gate for user-supplied files, so a malformed middle- // line is reported as 400 rather than silently dropped (read paths skip it instead).- records = parseTraceLines(content, { onMalformed: "throw" });- } catch {- throw invalid("The file is not valid Trace JSONL.");- }- if (records.length === 0) throw invalid("The file contains no Trace records.");- const first = records[0]!;- if (!isSessionMeta(first))- throw invalid("The first record of a Trace file must be session_meta.");- // The payload type declares session_id: string, but the value came from user-supplied JSON —- // re-check the runtime shape before it becomes part of a filename.- const sessionId: unknown = (first.payload as { session_id?: unknown }).session_id;- if (typeof sessionId !== "string" || !IMPORT_SESSION_ID_RE.test(sessionId)) {- throw invalid("session_meta carries a missing or invalid session_id.");- }- const duplicate = () =>- new HttpError(- 409,- "trace_session_exists",- `A Session with id ${sessionId} already exists here; a duplicate Trace cannot be imported.`,- );+ const bundle = parseTraceBundle(content);+ if (bundle !== null) return this.importTraceBundle(projectId, agentId, bundle);+ const shard = parseTraceShard(content, "The file");// A Session id is the identity everywhere — the sessions table keys on it, the frontend// dedupes rows by it, and /chat/:sessionId routes by it — so the check spans the whole// install, not just the receiving Agent. Importing the same Trace under a second Agent// used to "succeed" into a Session nothing could own: no row could be inserted beside// the existing one, and the list folded the two into a single conversation, leaving a// group's count one above the rows it could ever show.+ await this.assertTraceImportable(projectId, agentId, shard.sessionId);+ const dir = path.join(tracesDir(this.root, projectId, agentId), shard.date);+ await fs.mkdir(dir, { recursive: true });+ const written = await this.writeImportedShard(+ dir,+ shard.sessionId,+ 1,+ content,+ this.duplicateSession(shard.sessionId),+ );+ // Write-time registration: this path knows the file's identity and already holds the+ // parsed records, so the index row + session facts land synchronously (no re-read).+ this.index.registerImportedFile({+ projectId,+ agentId,+ sessionId: shard.sessionId,+ fileIndex: 1,+ date: shard.date,+ sizeBytes: written.sizeBytes,+ records: shard.records,+ });+ this.indexImportedSession(projectId, agentId, shard.sessionId);+ return { sessionId: shard.sessionId, index: 1, date: shard.date, shards: 1 };+ }++ /** 409 for a session id this install already has (a Trace may only ever create a Session). */+ private duplicateSession(sessionId: string): () => HttpError {+ return () =>+ new HttpError(+ 409,+ "trace_session_exists",+ `A Session with id ${sessionId} already exists here; a duplicate Trace cannot be imported.`,+ );+ }++ /** Rejects an import whose session id this install already has, under any Agent. */+ private async assertTraceImportable(+ projectId: string,+ agentId: string,+ sessionId: string,+ ): Promise<void> {+ const duplicate = this.duplicateSession(sessionId);if ((await this.locateAll(projectId, agentId, sessionId)).length > 0) throw duplicate();if (this.sessions?.findById?.(sessionId)) throw duplicate();- const ts = Date.parse(first.timestamp);- const date = formatLocalDate(Number.isNaN(ts) ? new Date() : new Date(ts));- const index = 1;- const dir = path.join(tracesDir(this.root, projectId, agentId), date);- await fs.mkdir(dir, { recursive: true });- const file = path.join(dir, `${sessionId}_${String(index).padStart(3, "0")}.jsonl`);+ }++ /**+ * Writes one imported shard as `<sessionId>_<index>.jsonl`, normalized to exactly one+ * trailing newline (the JSONL convention the writer follows). `wx` closes the check-then-write+ * race: two concurrent imports of the same new session id both pass the pre-check, but only+ * one can create the file — the loser's EEXIST maps to `onExists`'s 409.+ */+ private async writeImportedShard(+ dir: string,+ sessionId: string,+ index: number,+ content: string,+ onExists: () => HttpError,+ ): Promise<{ file: string; sizeBytes: number }> {const body = content.replace(/\n+$/, "") + "\n";+ const file = path.join(dir, `${sessionId}_${String(index).padStart(3, "0")}.jsonl`);try {- // Normalize to exactly one trailing newline (the JSONL convention the writer- // follows). `wx` closes the check-then-write race: two concurrent imports of the- // same new session id both pass the locateAll check, but only one can create the- // file — the loser's EEXIST maps to the same 409 as the pre-check.await fs.writeFile(file, body, { encoding: "utf8", flag: "wx" });} catch (err) {- if ((err as NodeJS.ErrnoException).code === "EEXIST") throw duplicate();+ if ((err as NodeJS.ErrnoException).code === "EEXIST") throw onExists();throw err;}- // Write-time registration: this path knows the file's identity and already holds the- // parsed records, so the index row + session facts land synchronously (no re-read).- this.index.registerImportedFile({- projectId,- agentId,- sessionId,- fileIndex: index,- date,- sizeBytes: Buffer.byteLength(body, "utf8"),- records,+ return { file, sizeBytes: Buffer.byteLength(body, "utf8") };+ }++ /** The all-or-nothing half of `importTraceFile`: a bundle's shards land together or not at all. */+ private async importTraceBundle(+ projectId: string,+ agentId: string,+ bundle: TraceBundle,+ ): Promise<TraceImportResponse> {+ const total = bundle.shards.length;+ // Validate every shard's content up front — including that each one belongs to the+ // Session the bundle names — before a single byte is written.+ const shards = bundle.shards.map((shard) => {+ const what = `Shard ${shard.index} of ${total}`;+ const parsed = parseTraceShard(shard.content, what);+ if (parsed.sessionId !== bundle.sessionId) {+ throw new HttpError(+ 400,+ "invalid_trace",+ `${what} belongs to Session ${parsed.sessionId}, not ${bundle.sessionId}.`,+ );+ }+ return { index: shard.index, content: shard.content, ...parsed };});- this.indexImportedSession(projectId, agentId, sessionId);- return { sessionId, index, date };+ await this.assertTraceImportable(projectId, agentId, bundle.sessionId);+ const duplicate = this.duplicateSession(bundle.sessionId);+ const written: { file: string; sizeBytes: number; shard: (typeof shards)[number] }[] = [];+ try {+ for (const shard of shards) {+ const dir = path.join(tracesDir(this.root, projectId, agentId), shard.date);+ await fs.mkdir(dir, { recursive: true });+ const file = await this.writeImportedShard(+ dir,+ bundle.sessionId,+ shard.index,+ shard.content,+ duplicate,+ );+ written.push({ ...file, shard });+ }+ } catch (err) {+ // Index rows are registered only once every file has landed, so removing the files is the+ // whole rollback: no half-imported Session, and nothing for the next import to trip over.+ for (const { file } of written) await fs.rm(file, { force: true });+ throw err;+ }+ for (const { sizeBytes, shard } of written) {+ this.index.registerImportedFile({+ projectId,+ agentId,+ sessionId: bundle.sessionId,+ fileIndex: shard.index,+ date: shard.date,+ sizeBytes,+ records: shard.records,+ });+ }+ this.indexImportedSession(projectId, agentId, bundle.sessionId);+ return {+ sessionId: bundle.sessionId,+ index: 1,+ date: shards[0]!.date,+ shards: total,+ };}/**diff --git a/packages/server/test/trace-import-export.test.ts b/packages/server/test/trace-import-export.test.tsindex 6f397a7f..4b7a6b38 100644--- a/packages/server/test/trace-import-export.test.ts+++ b/packages/server/test/trace-import-export.test.ts@@ -1,11 +1,14 @@/*** Trace file export/import integration tests:- * export serves the raw JSONL verbatim as an attachment (any member); import validates the+ * export serves the raw JSONL verbatim as an attachment (any member), and the whole-Session+ * bundle export serves every shard of one Session in a single file; import validates the* uploaded content (parseable JSONL, leading session_meta, filename-safe session_id) and* always stores it as index 1 of a new Session — a session id that exists ANYWHERE in the- * install is rejected with 409 trace_session_exists — the imported file becomes a listed- * Session of the receiving Agent, and is browsable through the existing tree/detail- * endpoints. Import is owner-only, mirroring the Agent snapshot import.+ * install is rejected with 409 trace_session_exists — unless the upload is a bundle, which+ * lands all of its shards as indices 1..N of ONE Session (validated in full first, so a+ * rejected bundle writes nothing); the imported files become a listed Session of the receiving+ * Agent, browsable through the existing tree/detail endpoints. Import is owner-only, mirroring+ * the Agent snapshot import.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import type { OmniMessage, SessionMetaPayload } from "@lmliheng/penguin-core";@@ -13,6 +16,7 @@ import type {AgentTracesResponse,ProjectCreateResponse,SessionsResponse,+ TraceBundle,TraceEventsResponse,TraceImportResponse,} from "../src/api/types.js";@@ -66,6 +70,30 @@ function localDateOf(iso: string): string {return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;}+/** A second shard of the same Session — what compaction rotates into: a new context, same id. */+const SECOND_TS = "2026-07-07T02:00:00.000Z";++function sampleTail(sessionId: string): OmniMessage[] {+ return [+ rec(SECOND_TS, "session_meta", metaPayload(sessionId)),+ rec("2026-07-07T02:00:01.000Z", "model_msg", {+ type: "text",+ role: "user",+ text: "second shard",+ }),+ ];+}++/** A migration bundle's upload content, shards numbered from 1 in the order given. */+function bundleContent(sessionId: string, shards: OmniMessage[][]): string {+ return JSON.stringify({+ format: "adelie-trace-bundle",+ version: 1,+ sessionId,+ shards: shards.map((messages, i) => ({ index: i + 1, content: toContent(messages) })),+ });+}+const toContent = (messages: OmniMessage[]): string =>messages.map((m) => JSON.stringify(m)).join("\n") + "\n";const b64 = (s: string): string => Buffer.from(s, "utf8").toString("base64");@@ -140,7 +168,7 @@ describe("trace-import-export", () => {const res = await owner.post(`${base()}/import`, { dataBase64: b64(content) });expect(res.status).toBe(200);const body = (await res.json()) as TraceImportResponse;- expect(body).toEqual({ sessionId: SID, index: 1, date: localDateOf(FIRST_TS) });+ expect(body).toEqual({ sessionId: SID, index: 1, date: localDateOf(FIRST_TS), shards: 1 });// Appears in the drill-down tree under the local date derived from the first record's timestamp.const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;expect(tree.dates).toHaveLength(1);@@ -275,6 +303,145 @@ describe("trace-import-export", () => {expect(res.status).toBe(400);});+ it("export bundle: every shard of the Session, verbatim, as one attachment (any member)", async () => {+ await writeTraceFile(+ t.root,+ projectId,+ "default_agent",+ "2026-07-06",+ SID,+ 1,+ sampleTrace(SID),+ );+ await writeTraceFile(t.root, projectId, "default_agent", "2026-07-07", SID, 2, sampleTail(SID));+ // A plain member can export the whole Session too (same rule as the snapshot export).+ const res = await member.get(`${base()}/${SID}/export`);+ expect(res.status).toBe(200);+ expect(res.headers.get("content-type")).toBe("application/json");+ expect(res.headers.get("content-disposition")).toBe(+ `attachment; filename*=UTF-8''${SID}.trace-bundle.json`,+ );+ const bundle = (await res.json()) as TraceBundle;+ expect(bundle.format).toBe("adelie-trace-bundle");+ expect(bundle.version).toBe(1);+ expect(bundle.sessionId).toBe(SID);+ expect(bundle.shards.map((s) => s.index)).toEqual([1, 2]);+ // Byte-for-byte the files on disk — the same content a per-file export serves.+ expect(bundle.shards[0]!.content).toBe(toContent(sampleTrace(SID)));+ expect(bundle.shards[1]!.content).toBe(toContent(sampleTail(SID)));+ });++ it("export bundle: a Session with no Trace → 404 trace_not_found", async () => {+ const res = await owner.get(`${base()}/${SID}/export`);+ expect(res.status).toBe(404);+ expect(await errorCode(res)).toBe("trace_not_found");+ });++ it("bundle import: every shard lands as ONE Session, browsable end to end", async () => {+ const res = await owner.post(`${base()}/import`, {+ dataBase64: b64(bundleContent(SID, [sampleTrace(SID), sampleTail(SID)])),+ });+ expect(res.status).toBe(200);+ const imported = (await res.json()) as TraceImportResponse;+ expect(imported).toEqual({+ sessionId: SID,+ index: 1,+ date: localDateOf(FIRST_TS),+ shards: 2,+ });+ // Each shard landed in its own date dir (derived from its own first record), and the second+ // is readable through the very endpoints a recorded shard uses.+ const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;+ expect(tree.dates.map((d) => d.date).sort()).toEqual(+ [localDateOf(FIRST_TS), localDateOf(SECOND_TS)].sort(),+ );+ const shard = (await (await owner.get(`${base()}/${SID}/2`)).json()) as TraceEventsResponse;+ expect(shard.total).toBe(2);+ expect((shard.events[1]!.payload as { text: string }).text).toBe("second shard");+ // One conversation, not one per shard: the imported Session is listed once.+ const listed = (await (+ await owner.get(`/api/projects/${projectId}/agents/default_agent/sessions?counts=1`)+ ).json()) as SessionsResponse;+ expect(listed.sessions.map((x) => x.sessionId)).toEqual([SID]);+ });++ it("bundle import: a shard out of order → 400, nothing written", async () => {+ // Contiguity from 1 is what keeps the landed filenames a copy of the original Session: a+ // gap would silently reorder the transcript, so it is refused before anything is written.+ const res = await owner.post(`${base()}/import`, {+ dataBase64: b64(+ JSON.stringify({+ format: "adelie-trace-bundle",+ version: 1,+ sessionId: SID,+ shards: [+ { index: 1, content: toContent(sampleTrace(SID)) },+ { index: 3, content: toContent(sampleTail(SID)) },+ ],+ }),+ ),+ });+ expect(res.status).toBe(400);+ expect(await errorCode(res)).toBe("invalid_trace");+ const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;+ expect(tree.dates).toEqual([]);+ });++ it("bundle import: a shard belonging to another Session → 400, nothing written", async () => {+ const other = "session-2026-07-07-09-00-00-feed0002";+ const res = await owner.post(`${base()}/import`, {+ dataBase64: b64(bundleContent(SID, [sampleTrace(SID), sampleTail(other)])),+ });+ expect(res.status).toBe(400);+ expect(await errorCode(res)).toBe("invalid_trace");+ const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;+ expect(tree.dates).toEqual([]);+ });++ it("bundle import: a malformed shard stops the whole import (all-or-nothing)", async () => {+ const res = await owner.post(`${base()}/import`, {+ dataBase64: b64(+ JSON.stringify({+ format: "adelie-trace-bundle",+ version: 1,+ sessionId: SID,+ shards: [+ { index: 1, content: toContent(sampleTrace(SID)) },+ { index: 2, content: "{not json" },+ ],+ }),+ ),+ });+ expect(res.status).toBe(400);+ expect(await errorCode(res)).toBe("invalid_trace");+ // Shard 1 was valid, yet nothing of it is on disk: a bundle lands whole or not at all.+ const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;+ expect(tree.dates).toEqual([]);+ });++ it("bundle import: duplicate session id → 409, the existing Session untouched", async () => {+ await writeTraceFile(+ t.root,+ projectId,+ "default_agent",+ "2026-07-06",+ SID,+ 1,+ sampleTrace(SID),+ );+ const res = await owner.post(`${base()}/import`, {+ dataBase64: b64(bundleContent(SID, [sampleTrace(SID), sampleTail(SID)])),+ });+ expect(res.status).toBe(409);+ expect(await errorCode(res)).toBe("trace_session_exists");+ const tree = (await (await owner.get(base())).json()) as AgentTracesResponse;+ expect(tree.dates).toHaveLength(1);+ expect(tree.dates[0]!.sessions[0]!.files.map((f) => f.index)).toEqual([1]);+ expect(await (await owner.get(`${base()}/${SID}/1/download`)).text()).toBe(+ toContent(sampleTrace(SID)),+ );+ });+it("import: owner only — member 403, outsider 404, unknown agent 404", async () => {const body = { dataBase64: b64(toContent(sampleTrace(SID))) };expect((await member.post(`${base()}/import`, body)).status).toBe(403);diff --git a/packages/server/test/trace-index.test.ts b/packages/server/test/trace-index.test.tsindex a081aaf3..cccd73ce 100644--- a/packages/server/test/trace-index.test.ts+++ b/packages/server/test/trace-index.test.ts@@ -190,7 +190,7 @@ describe("trace-index", () => {.join("\n");const headReads = h.traceIndex.counters.headReads;const res = await h.service.importTraceFile(P, A, lines);- expect(res).toEqual({ sessionId: IMP, index: 1, date: "2026-07-03" });+ expect(res).toEqual({ sessionId: IMP, index: 1, date: "2026-07-03", shards: 1 });// Registered without any head-read (the records were already in memory).expect(h.traceIndex.counters.headReads).toBe(headReads);expect(h.traceIndex.repo.listFilesBySession(P, A, IMP)).toHaveLength(1);diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex 016a00de..6eb6524a 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -108,6 +108,7 @@ import type {SubagentMessageResponse,TaskCreateResponse,TraceAnalysisResponse,+ TraceBundle,TraceEventsResponse,TraceImportResponse,UpdateCheckResponse,@@ -1570,35 +1571,52 @@ const traceEvents = (ctx: Ctx, sessionId: string): TraceEventsResponse => {};};+/**+ * The demo transcript stands in for a Session that was compacted once, so the Trace panel's+ * multi-shard shape is what the gallery shows: one pill per shard, and the whole-Session export+ * offered beside the per-file one.+ */+const TRACE_SHARDS = [1, 2];++/** A shard's JSON Lines content: the demo transcript, written the way the Trace Writer would. */+const traceShardContent = (ctx: Ctx, sessionId: string): string =>+ traceFile(ctx, sessionId)+ .transcript.history.map((m) => JSON.stringify(m))+ .join("\n");+const traceJsonl = (ctx: Ctx, sessionId: string) =>- raw(- traceFile(ctx, sessionId)- .transcript.history.map((m) => JSON.stringify(m))- .join("\n"),- {- "content-type": "application/x-ndjson",- "content-disposition": `attachment; filename="${sessionId}-001.jsonl"`,- },- );+ raw(traceShardContent(ctx, sessionId), {+ "content-type": "application/x-ndjson",+ "content-disposition": `attachment; filename="${sessionId}-001.jsonl"`,+ });++/** Whole-Session bundle: the same content that the per-file download serves, every shard of it. */+const traceBundle = (ctx: Ctx, sessionId: string): TraceBundle => ({+ format: "adelie-trace-bundle",+ version: 1,+ sessionId,+ shards: TRACE_SHARDS.map((index) => ({ index, content: traceShardContent(ctx, sessionId) })),+});router.get("/api/sessions/:sessionId/traces", (ctx): SessionTracesResponse => {const { transcript, row } = traceFile(ctx, ctx.params.sessionId!);return {- files: [- {- index: 1,- date: dayKey(Date.parse(row.createdAt)),- sizeBytes: JSON.stringify(transcript.history).length,- mtime: row.lastActiveAt,- },- ],+ files: TRACE_SHARDS.map((index) => ({+ index,+ date: dayKey(Date.parse(row.createdAt)),+ sizeBytes: JSON.stringify(transcript.history).length,+ mtime: row.lastActiveAt,+ })),};}).get("/api/sessions/:sessionId/traces/:index", (ctx) => traceEvents(ctx, ctx.params.sessionId!)).get("/api/sessions/:sessionId/traces/:index/analysis", (ctx): TraceAnalysisResponse =>analyze(traceFile(ctx, ctx.params.sessionId!).transcript.history),)+ .get("/api/projects/:projectId/agents/:agentId/traces/:sessionId/export", (ctx) =>+ json(traceBundle(ctx, ctx.params.sessionId!), 200),+ ).get("/api/projects/:projectId/agents/:agentId/traces/:sessionId/:index", (ctx) =>traceEvents(ctx, ctx.params.sessionId!),)@@ -1612,7 +1630,12 @@ router).post("/api/projects/:projectId/agents/:agentId/traces/import", (): unknown =>json(- { sessionId: "s-imported", index: 1, date: dayKey(Date.now()) } satisfies TraceImportResponse,+ {+ sessionId: "s-imported",+ index: 1,+ date: dayKey(Date.now()),+ shards: 1,+ } satisfies TraceImportResponse,201,),);diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 3ce3641c..f4c8bbe8 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -1338,7 +1338,27 @@ export const agentTraceDownloadUrl = (machineForSession(sessionId),);-/** Imports a Trace JSONL file (owner only); the response says where the file landed (sessionId / index / date). */+/**+ * Whole-Session export URL: every shard of the Session as one bundle file, for import on another+ * install. A plain browser-followed URL like the per-file download, so it is usable directly in+ * `<a download>`.+ */+export const agentTraceBundleExportUrl = (+ projectId: string,+ agentId: string,+ sessionId: string,+): string =>+ apiUrl(+ `/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}` ++ `/traces/${encodeURIComponent(sessionId)}/export`,+ machineForSession(sessionId),+ );++/**+ * Imports a Trace file (owner only): a single `.jsonl` Trace, or a whole-Session `.json` bundle+ * exported from another install. The response says where it landed (sessionId / index / date /+ * shard count).+ */export const importAgentTrace = (projectId: string, agentId: string, body: TraceImportRequest) =>apiFetch<TraceImportResponse>(`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/traces/import`,diff --git a/packages/web/src/features/settings/trace-import-row.tsx b/packages/web/src/features/settings/trace-import-row.tsxindex 1ac2f1d2..80628e6f 100644--- a/packages/web/src/features/settings/trace-import-row.tsx+++ b/packages/web/src/features/settings/trace-import-row.tsx@@ -1,6 +1,7 @@/**- * Trace import (Settings → General): a `.jsonl` Trace exported from another install- * becomes a conversation of the chosen Agent.+ * Trace import (Settings → General): a `.jsonl` Trace — or a whole-Session `.json` bundle, which+ * carries every shard of a compacted Session — exported from another install becomes a+ * conversation of the chosen Agent.** Both halves of the destination are picked here, Project included. The endpoint is* per-Agent and a Trace file cannot name one: its `session_meta` carries an `agent_state`@@ -35,6 +36,8 @@ import { useSessions } from "../../state/sessions";/** Client-side pre-check before reading the picked file (the same cap as the server's import route). */const MAX_TRACE_BYTES = 14 * 1024 * 1024;+/** A whole-Session bundle is several shards in one file, so it gets the server's larger ceiling. */+const MAX_TRACE_BUNDLE_BYTES = 48 * 1024 * 1024;/*** The Projects the row offers, and the one it is on. The import route answers anyone but the@@ -129,8 +132,11 @@ export function TraceImportRow() {// Reset before reading so re-picking the same file fires change again.e.target.value = "";if (!file || agentId === "") return;- if (file.size > MAX_TRACE_BYTES) {- toastError(S.settings.importTraceTooLarge);+ // Which ceiling applies is decided by the file, the same way the server decides it: a+ // `.json` bundle may be several shards' worth, a `.jsonl` Trace file is one shard.+ const bundle = file.name.toLowerCase().endsWith(".json");+ if (file.size > (bundle ? MAX_TRACE_BUNDLE_BYTES : MAX_TRACE_BYTES)) {+ toastError(bundle ? S.settings.importTraceBundleTooLarge : S.settings.importTraceTooLarge);return;}const reader = new FileReader();@@ -196,7 +202,7 @@ export function TraceImportRow() {: "cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-800"}`}>- <HiddenFileInput accept=".jsonl" disabled={busy} onChange={onPickFile} />+ <HiddenFileInput accept=".jsonl,.json" disabled={busy} onChange={onPickFile} /><UploadIcon size={14} />{importing ? S.settings.importTraceRunning : S.settings.importTracePick}</label>diff --git a/packages/web/src/features/traces/trace-panel.tsx b/packages/web/src/features/traces/trace-panel.tsxindex d2a219c5..8efdb9eb 100644--- a/packages/web/src/features/traces/trace-panel.tsx+++ b/packages/web/src/features/traces/trace-panel.tsx@@ -189,6 +189,24 @@ export function TracePanel({<DownloadIcon size={ICON_SIZE.rowLead} />{S.traces.exportFile}</a>+ {/* Whole-Session export: one bundle file holding every compaction shard, so a long+ Session can be moved to another install in one piece. Only offered when the Session+ really has several shards — with one, the per-file download above IS the Session. */}+ {files.length > 1 && (+ <a+ href={api.agentTraceBundleExportUrl(+ session.projectId,+ session.agentId,+ session.sessionId,+ )}+ download+ data-tooltip={S.traces.exportSessionHint}+ className="inline-flex shrink-0 items-center gap-1 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 dark:border-gray-800 dark:text-gray-400 dark:hover:bg-gray-800/60"+ >+ <DownloadIcon size={ICON_SIZE.rowLead} />+ {S.traces.exportSession}+ </a>+ )}</div>{/* The listing tick doubles as the view's re-read signal: every edge that re-listsdiff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 695355fe..f4bf4c94 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -391,13 +391,14 @@ export const en: Strings = {/** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */importTrace: "Import Trace",importTraceInfo:- "Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",+ "Upload a .jsonl Trace exported from another install and it becomes a conversation of the chosen Agent — or the .json bundle from a conversation's \"Export whole session\", which brings every shard of a long Session along. Both halves of the destination are picked here: the endpoint is per-Agent — a Trace file's own session_meta cannot name a local Agent, since its agent_state path belongs to the machine that exported it — and the Project is asked for because this dialog does not show which one is open, which also means a Trace can go to a Project other than the open one. Exporting happens in a conversation's Trace panel.",importTraceProject: "Import into project",importTraceAgent: "Import into agent",importTracePick: "Choose file",importTraceRunning: "Importing…",importTraceDone: (target: string) => `Trace imported into ${target}`,importTraceTooLarge: "The file exceeds the 14MB limit.",+ importTraceBundleTooLarge: "The session bundle exceeds the 48MB limit.",/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "Proxy options",proxyInfo:@@ -4100,6 +4101,10 @@ export const en: Strings = {systemPrompt: "System prompt",toolDefs: (n: number) => `Tool definitions (${n})`,exportFile: "Export",+ /** Whole-Session export: every compaction shard in one file, for import on another install. */+ exportSession: "Export whole session",+ exportSessionHint:+ "Pack every shard of this Session into one file, importable in another Adelie",},benchmark: {diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex 23902b60..78af7a28 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -460,13 +460,14 @@ export const zh = {/** Trace import: the two pickers' accessible names, the pick-a-file action, and its outcomes. */importTrace: "导入 Trace",importTraceInfo:- "上传从其他部署导出的 .jsonl 轨迹文件,它会成为所选 Agent 的一个会话。目的地的两个部分都在这里选择:导入接口按 Agent 划分——轨迹文件自带的 session_meta 无法指认本机的 Agent,其中的 agent_state 路径属于导出它的那台机器——而项目需要明确指定,因为本对话框不显示当前是哪一个,也因此可以导入到当前打开之外的项目。导出在对话的 Trace 面板中进行。",+ "上传从其他部署导出的 .jsonl 轨迹文件,它会成为所选 Agent 的一个会话;也可以上传对话的 Trace 面板里「导出整个会话」得到的 .json 包,那会把一个长会话的全部分片一起带过来。目的地的两个部分都在这里选择:导入接口按 Agent 划分——轨迹文件自带的 session_meta 无法指认本机的 Agent,其中的 agent_state 路径属于导出它的那台机器——而项目需要明确指定,因为本对话框不显示当前是哪一个,也因此可以导入到当前打开之外的项目。导出在对话的 Trace 面板中进行。",importTraceProject: "导入到项目",importTraceAgent: "导入到 Agent",importTracePick: "选择文件",importTraceRunning: "导入中…",importTraceDone: (target: string) => `轨迹已导入到 ${target}`,importTraceTooLarge: "文件超过 14MB 上限。",+ importTraceBundleTooLarge: "整会话包超过 48MB 上限。",/** Admin-only sub-page (server-global); its explanation is disclosed at the pane heading. */proxyTitle: "代理选项",proxyInfo:@@ -4133,6 +4134,9 @@ export const zh = {systemPrompt: "系统提示词",toolDefs: (n: number) => `工具定义(${n})`,exportFile: "导出",+ /** Whole-Session export: every compaction shard in one file, for import on another install. */+ exportSession: "导出整个会话",+ exportSessionHint: "把这个会话的全部分片打包成一个文件,可在另一台 Adelie 导入",},benchmark: {