@devries-cameron20 / t3code Mirror · read-only / commits / 3e482550fc
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 23:15 UTC

fix(server): import long Claude sessions that are mostly tool records (#19161)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Michael Shih committed Oct 19, 2026 at 22:06 UTC 3e482550fccea7f75b6c828bf161a8178ad55cc2
2 files changed +202 -51
apps/server/src/project/AgentSessionScanner.test.ts
+125
@@ -2115,6 +2115,131 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
2115 }),
2116 );
2117
2118 + it.effect("imports long Claude tool history with metadata from discarded records", () =>
2119 + Effect.gen(function* () {
2120 + const path = yield* Path.Path;
2121 + const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2122 + yield* TestClock.setTime(nowMs);
2123 + const claudeHomePath = yield* makeTempDir("t3code-long-claude-");
2124 + const codexHomePath = yield* makeTempDir("t3code-long-codex-");
2125 + const workspace = yield* makeTempDir("t3code-long-workspace-");
2126 + const record = (fields: Record<string, unknown>) =>
2127 + encodeTranscriptRecord({ sessionId: "first-session", ...fields });
2128 + const toolResult = record({
2129 + type: "user",
2130 + cwd: path.join(workspace, "later-cwd"),
2131 + message: {
2132 + role: "user",
2133 + content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }],
2134 + },
2135 + });
2136 + yield* writeTranscript({
2137 + filePath: path.join(claudeHomePath, "projects", "-slug", "long-session.jsonl"),
2138 + contents: [
2139 + record({ type: "attachment", cwd: workspace, aiTitle: "Old title" }),
2140 + record({ type: "user", message: { role: "user", content: "First prompt" } }),
2141 + record({
2142 + type: "assistant",
2143 + message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" },
2144 + }),
2145 + // Small tool records exceed the real 32 MiB selected-history budget in aggregate.
2146 + ...Array.from({ length: 20_000 }, () => toolResult),
2147 + record({ type: "user", message: { role: "user", content: "Latest prompt" } }),
2148 + record({
2149 + type: "assistant",
2150 + message: {
2151 + role: "assistant",
2152 + model: "claude-sonnet-5-5",
2153 + content: [{ type: "tool_use", id: "toolu_1", name: "Bash", input: {} }],
2154 + },
2155 + }),
2156 + record({ type: "custom-title", customTitle: "Renamed conversation" }),
2157 + record({ type: "ai-title", aiTitle: "Newest title" }),
2158 + record({ type: "attachment", sessionId: "latest-session" }),
2159 + ].join("\n"),
2160 + mtimeMs: nowMs,
2161 + });
2162 +
2163 + const threads = yield* runRecentThreads({
2164 + claudeHomePath,
2165 + codexHomePath,
2166 + workspaceRoot: workspace,
2167 + });
2168 +
2169 + expect(threads).toMatchObject([
2170 + {
2171 + providerSessionId: "latest-session",
2172 + title: "Renamed conversation",
2173 + model: "claude-sonnet-5-5",
2174 + messages: [
2175 + { role: "user", text: "First prompt" },
2176 + { role: "assistant", text: "First reply" },
2177 + { role: "user", text: "Latest prompt" },
2178 + ],
2179 + },
2180 + ]);
2181 + }),
2182 + );
2183 +
2184 + it.effect("excludes hidden Claude records from the history budget and session metadata", () =>
2185 + Effect.gen(function* () {
2186 + const path = yield* Path.Path;
2187 + const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
2188 + yield* TestClock.setTime(nowMs);
2189 + const claudeHomePath = yield* makeTempDir("t3code-hidden-claude-");
2190 + const codexHomePath = yield* makeTempDir("t3code-hidden-codex-");
2191 + const workspace = yield* makeTempDir("t3code-hidden-workspace-");
2192 + const message = (role: "user" | "assistant", text: string) =>
2193 + encodeTranscriptRecord({
2194 + sessionId: "visible-session",
2195 + cwd: workspace,
2196 + type: role,
2197 + message: { role, content: text },
2198 + });
2199 + const flags = ["isSidechain", "isMeta", "isCompactSummary"] as const;
2200 + // Each hidden reply selects about 2 MiB; together they exceed the real 32 MiB budget.
2201 + const hiddenReply = (flag: (typeof flags)[number]) =>
2202 + encodeTranscriptRecord({
2203 + sessionId: "hidden-session",
2204 + aiTitle: "Hidden title",
2205 + customTitle: "Hidden rename",
2206 + type: "assistant",
2207 + [flag]: true,
2208 + message: { role: "assistant", model: "hidden-model", content: "x".repeat(1024 * 1024) },
2209 + });
2210 + yield* writeTranscript({
2211 + filePath: path.join(claudeHomePath, "projects", "-slug", "hidden-session.jsonl"),
2212 + contents: [
2213 + message("user", "First prompt"),
2214 + message("assistant", "First reply"),
2215 + ...Array.from({ length: 20 }, (_, index) => hiddenReply(flags[index % flags.length]!)),
2216 + message("user", "Latest prompt"),
2217 + hiddenReply("isSidechain"),
2218 + ].join("\n"),
2219 + mtimeMs: nowMs,
2220 + });
2221 +
2222 + const threads = yield* runRecentThreads({
2223 + claudeHomePath,
2224 + codexHomePath,
2225 + workspaceRoot: workspace,
2226 + });
2227 +
2228 + expect(threads).toMatchObject([
2229 + {
2230 + providerSessionId: "visible-session",
2231 + title: "First prompt",
2232 + model: null,
2233 + messages: [
2234 + { role: "user", text: "First prompt" },
2235 + { role: "assistant", text: "First reply" },
2236 + { role: "user", text: "Latest prompt" },
2237 + ],
2238 + },
2239 + ]);
2240 + }),
2241 + );
2242 +
2243 it.effect("reports stat, read, and parse failures as skipped", () =>
2244 Effect.gen(function* () {
2245 const path = yield* Path.Path;
apps/server/src/project/AgentSessionScanner.ts
+77 -51
@@ -215,16 +215,17 @@ function splitTranscriptRecords(contents: string, limit: number): string[] {
215 return records.split("\n", limit);
216 }
217
218 +function isTextContentBlock(block: typeof TranscriptContentBlock.Type): boolean {
219 + return block.type === "text" || block.type === "input_text" || block.type === "output_text";
220 +}
221 +
222 function extractText(
223 content: string | ReadonlyArray<typeof TranscriptContentBlock.Type> | undefined,
224 ): string {
225 if (typeof content === "string") return content.trim();
226 if (content === undefined) return "";
227 return content
224 - .filter(
225 - (block) =>
226 - block.type === "text" || block.type === "input_text" || block.type === "output_text",
227 - )
228 + .filter(isTextContentBlock)
229 .map((block) => block.text?.trim() ?? "")
230 .filter((text) => text.length > 0)
231 .join("\n");
@@ -248,6 +249,40 @@ function codexTurnId(metadata: unknown): string | null {
249 return decoded.value.turn_id;
250 }
251
252 +function isHiddenClaudeRecord(record: DecodedTranscriptRecord): boolean {
253 + return record.isSidechain === true || record.isMeta === true || record.isCompactSummary === true;
254 +}
255 +
256 +// Claude repeats session fields on records that need not be retained.
257 +interface ClaudeFields {
258 + readonly sessionId: string | undefined;
259 + readonly title: string | undefined;
260 + readonly customTitle: string | null;
261 + readonly model: string | undefined;
262 +}
263 +
264 +const emptyClaudeFields: ClaudeFields = {
265 + sessionId: undefined,
266 + title: undefined,
267 + customTitle: null,
268 + model: undefined,
269 +};
270 +
271 +function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord): ClaudeFields {
272 + if (isHiddenClaudeRecord(record)) return fields;
273 + const model = record.message?.model?.trim();
274 + return {
275 + sessionId: record.sessionId?.trim() || fields.sessionId,
276 + title: record.aiTitle?.trim() || fields.title,
277 + // Claude flushes the AI title after the user's rename; an empty rename clears it.
278 + customTitle:
279 + record.customTitle === undefined ? fields.customTitle : record.customTitle.trim() || null,
280 + // Claude uses this sentinel for local error responses. It is not a
281 + // model ID that can be selected when the imported session resumes.
282 + model: model && model !== "<synthetic>" ? model : fields.model,
283 + };
284 +}
285 +
286 // Codex records setup context as user text ahead of the real request. Skip
287 // these leading blocks when deriving a title; imported messages keep them.
288 const CODEX_TITLE_PREAMBLE =
@@ -266,21 +301,26 @@ export function parseAgentSessionTranscript(
301 ): AgentSessionThread | null {
302 if (lines.length > MAX_IMPORT_RECORDS) return null;
303 const records = lines.flatMap((line) => Option.toArray(decodeTranscriptRecord(line)));
269 - return parseAgentSessionRecords(input, records);
304 + const claudeFields =
305 + input.source === "claudeAgent"
306 + ? records.reduce(foldClaudeFields, emptyClaudeFields)
307 + : emptyClaudeFields;
308 + return parseAgentSessionRecords(input, records, claudeFields);
309 }
310
311 function parseAgentSessionRecords(
312 input: AgentSessionTranscriptMetadata,
313 records: ReadonlyArray<DecodedTranscriptRecord>,
314 + claudeFields: ClaudeFields,
315 ): AgentSessionThread | null {
316 const fallbackTimestamp = DateTime.formatIso(DateTime.makeUnsafe(input.lastActiveAtMs));
317 // Claude filenames are session IDs. Codex rollout filenames include extra
318 // timestamp text, so only transcript metadata can provide a resumable ID.
279 - let providerSessionId = input.source === "codex" ? "" : input.fallbackSessionId;
280 - let title: string | null = null;
281 - let customTitle: string | null = null;
319 + let providerSessionId =
320 + input.source === "codex" ? "" : (claudeFields.sessionId ?? input.fallbackSessionId);
321 + const title = claudeFields.title ?? null;
322 + let model = claudeFields.model ?? null;
323 let derivedTitle: string | undefined;
283 - let model: string | null = null;
324 let hasCodexSessionId = false;
325 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
326 let firstUserMessage:
@@ -372,27 +412,8 @@ function parseAgentSessionRecords(
412 for (const record of records) {
413 recordIndex += 1;
414 if (input.source === "claudeAgent") {
375 - if (
376 - record.isSidechain === true ||
377 - record.isMeta === true ||
378 - record.isCompactSummary === true
379 - ) {
380 - continue;
381 - }
382 - if (record.sessionId?.trim()) providerSessionId = record.sessionId.trim();
383 - if (record.aiTitle?.trim()) title = record.aiTitle.trim();
384 - // Claude rewrites both title records on every flush, so the user's
385 - // rename is tracked separately instead of racing the later ai-title.
386 - // An empty customTitle is how Claude clears a rename.
387 - if (record.customTitle !== undefined) customTitle = record.customTitle.trim() || null;
388 - const messageModel = record.message?.model?.trim();
389 - // Claude uses this sentinel for local error responses. It is not a
390 - // model ID that can be selected when the imported session resumes.
391 - if (messageModel && messageModel !== "<synthetic>") model = messageModel;
392 - if (record.type !== "user" && record.type !== "assistant") {
393 - continue;
394 - }
395 -
415 + if (isHiddenClaudeRecord(record)) continue;
416 + if (record.type !== "user" && record.type !== "assistant") continue;
417 const text = extractText(record.message?.content);
418 if (text.length === 0) continue;
419 retainMessage({
@@ -477,7 +498,7 @@ function parseAgentSessionRecords(
498 source: input.source,
499 providerInstanceId: input.providerInstanceId,
500 providerSessionId,
480 - title: customTitle ?? title ?? derivedTitle ?? "Imported thread",
501 + title: claudeFields.customTitle ?? title ?? derivedTitle ?? "Imported thread",
502 model,
503 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
504 updatedAt: fallbackTimestamp,
@@ -494,17 +515,18 @@ function shouldRetainDecodedRecord(
515 source: AgentSessionSource,
516 record: DecodedTranscriptRecord,
517 ): boolean {
497 - if (extractDecodedCwd(record) !== null) return true;
518 if (source === "claudeAgent") {
499 - return (
500 - record.type === "user" ||
501 - record.type === "assistant" ||
502 - record.sessionId !== undefined ||
503 - record.aiTitle !== undefined ||
504 - record.customTitle !== undefined ||
505 - record.message?.model !== undefined
506 - );
519 + if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) {
520 + return false;
521 + }
522 + const content = record.message?.content;
523 + return typeof content === "string"
524 + ? content.trim().length > 0
525 + : (content?.some(
526 + (block) => isTextContentBlock(block) && (block.text?.trim().length ?? 0) > 0,
527 + ) ?? false);
528 }
529 + if (extractDecodedCwd(record) !== null) return true;
530 return (
531 record.type === "session_meta" ||
532 record.type === "turn_context" ||
@@ -802,6 +824,8 @@ export const make = Effect.gen(function* () {
824 return null;
825 }
826 const records: Array<DecodedTranscriptRecord> = [];
827 + let cwd = Option.none<string>();
828 + let claudeFields = emptyClaudeFields;
829 let historyBytes = 0;
830 let recordBytes = 0;
831 let recordCount = 0;
@@ -823,9 +847,15 @@ export const make = Effect.gen(function* () {
847 recordCount += 1;
848 if (recordCount > recordLimit) return false;
849 const decoded = decodeTranscriptValue(reader.finish());
826 - if (Option.isSome(decoded) && shouldRetainDecodedRecord(source, decoded.value)) {
827 - records.push(decoded.value);
828 - historyBytes += recordBytes;
850 + if (Option.isSome(decoded)) {
851 + if (Option.isNone(cwd)) cwd = Option.fromNullOr(extractDecodedCwd(decoded.value));
852 + if (source === "claudeAgent") {
853 + claudeFields = foldClaudeFields(claudeFields, decoded.value);
854 + }
855 + if (shouldRetainDecodedRecord(source, decoded.value)) {
856 + records.push(decoded.value);
857 + historyBytes += recordBytes;
858 + }
859 }
860 recordBytes = 0;
861 reader = createTranscriptJsonReader(reserve, selectTranscriptPath);
@@ -861,7 +891,7 @@ export const make = Effect.gen(function* () {
891
892 if (recordStarted && !(yield* Effect.try(finishRecord))) return null;
893 return sameTranscriptIdentity(expected, transcriptIdentity(filePath, yield* file.stat))
864 - ? { records, recordCount }
894 + ? { records, recordCount, cwd, claudeFields }
895 : null;
896 }),
897 ),
@@ -1382,15 +1412,10 @@ export const make = Effect.gen(function* () {
1412 }
1413 recordsRemaining -= snapshot.recordCount;
1414
1385 - let snapshotCwd: string | null = null;
1386 - for (const record of snapshot.records) {
1387 - snapshotCwd = extractDecodedCwd(record);
1388 - if (snapshotCwd !== null) break;
1389 - }
1390 - if (snapshotCwd === null) {
1415 + if (Option.isNone(snapshot.cwd)) {
1416 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
1417 }
1393 - const expandedCwd = expandHomePath(snapshotCwd.trim(), homeDir);
1418 + const expandedCwd = expandHomePath(snapshot.cwd.value.trim(), homeDir);
1419 if (
1420 !path.isAbsolute(expandedCwd) ||
1421 (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
@@ -1406,6 +1431,7 @@ export const make = Effect.gen(function* () {
1431 lastActiveAtMs: transcript.mtimeMs,
1432 },
1433 snapshot.records,
1434 + snapshot.claudeFields,
1435 );
1436 if (parsedThread === null) {
1437 return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });