@devries-cameron20 / t3code-1 / commits / 486ba48380
Fork 0

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

fix(server): imported Claude threads show prompts, not Claude Code markup (#33403)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Dominik Žabčík committed Nov 18, 2026 at 10:07 UTC 486ba483804aa967f9cb0089e8128afd519dfcdd
3 files changed +166 -27
apps/server/src/project/AgentSessionScanner.test.ts
+90 -7
@@ -2676,15 +2676,25 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
2676 content: [{ type: "tool_result", tool_use_id: "toolu_1", content: "ok" }],
2677 },
2678 });
2679 + // Claude Code's own command output is not a message and must not take a history slot.
2680 + const commandOutput = record({
2681 + type: "user",
2682 + message: {
2683 + role: "user",
2684 + content: "<local-command-stdout>Compacted</local-command-stdout>",
2685 + },
2686 + });
2687 yield* writeTranscript({
2688 filePath: path.join(claudeHomePath, "projects", "-slug", "long-session.jsonl"),
2689 contents: [
2690 record({ type: "attachment", cwd: workspace, aiTitle: "Old title" }),
2691 + commandOutput,
2692 record({ type: "user", message: { role: "user", content: "First prompt" } }),
2693 record({
2694 type: "assistant",
2695 message: { role: "assistant", model: "claude-opus-5-5", content: "First reply" },
2696 }),
2697 + ...Array.from({ length: 200 }, () => commandOutput),
2698 // Small tool records exceed the real 32 MiB selected-history budget in aggregate.
2699 ...Array.from({ length: 20_000 }, () => toolResult),
2700 record({ type: "user", message: { role: "user", content: "Latest prompt" } }),
@@ -3284,6 +3294,20 @@ describe("parseAgentSessionTranscript", () => {
3294 sessionId: "claude-session",
3295 message: { role: "user", content: [{ type: "tool_result", text: "hidden" }] },
3296 }),
3297 + ...[
3298 + "<command-name>/review</command-name>\n<command-message>review</command-message>\n<command-args>the login flow</command-args>",
3299 + "<local-command-stdout>Enabled plan mode</local-command-stdout>",
3300 + "<bash-input>npm test</bash-input>",
3301 + "<bash-stdout>1 passed</bash-stdout><bash-stderr></bash-stderr>",
3302 + "<task-notification>\n<task-id>a1</task-id>\n<status>completed</status>\n</task-notification>",
3303 + "[Request interrupted by user for tool use]",
3304 + ].map((content) =>
3305 + JSON.stringify({
3306 + type: "user",
3307 + sessionId: "claude-session",
3308 + message: { role: "user", content },
3309 + }),
3310 + ),
3311 JSON.stringify({
3312 type: "assistant",
3313 sessionId: "claude-session",
@@ -3315,6 +3339,8 @@ describe("parseAgentSessionTranscript", () => {
3339 model: "claude-sonnet-5",
3340 messages: [
3341 { role: "user", text: "Fix authentication" },
3342 + { role: "user", text: "/review the login flow" },
3343 + { role: "user", text: "!npm test" },
3344 { role: "assistant", text: "Updated the login flow" },
3345 { role: "assistant", text: "The provider request failed" },
3346 ],
@@ -3325,6 +3351,16 @@ describe("parseAgentSessionTranscript", () => {
3351 { customTitles: ["Refactor auth module"], expected: "Refactor auth module" },
3352 // Claude writes an empty customTitle when the user clears a rename.
3353 { customTitles: ["Refactor auth module", ""], expected: "Generated title" },
3354 + // Some launchers rename the session to the raw markup of its opening command.
3355 + {
3356 + customTitles: ["<command-message>pstack:poteto-mode</command-message>"],
3357 + expected: "Generated title",
3358 + },
3359 + {
3360 + customTitles: ["<local-command-stdout>Enabled plan mode</local-command-stdout>"],
3361 + expected: "Generated title",
3362 + },
3363 + { customTitles: ["<bash-input>npm test</bash-input>"], expected: "Generated title" },
3364 ])("uses Claude custom titles $customTitles over the AI title", ({ customTitles, expected }) => {
3365 const aiTitle = JSON.stringify({
3366 type: "ai-title",
@@ -3337,7 +3373,7 @@ describe("parseAgentSessionTranscript", () => {
3373 type: "user",
3374 sessionId: "claude-session",
3375 timestamp: "2026-08-24T10:00:00.000Z",
3340 - message: { role: "user", content: "<command-name>/effort</command-name>" },
3376 + message: { role: "user", content: "Tighten the session checks" },
3377 }),
3378 // Claude rewrites both records on every metadata flush with ai-title
3379 // last, so a later ai-title must not override the user's rename.
@@ -3355,6 +3391,33 @@ describe("parseAgentSessionTranscript", () => {
3391 expect(thread?.title).toBe(expected);
3392 });
3393
3394 + it.each([
3395 + {
3396 + first:
3397 + "<command-name>/pstack:arena</command-name><command-args>Compare designs</command-args>",
3398 + title: "Compare designs",
3399 + },
3400 + {
3401 + first: "<command-name>/clear</command-name><command-message>clear</command-message>",
3402 + title: "Plan the release",
3403 + },
3404 + { first: "/Users/me/app fails to build", title: "/Users/me/app fails to build" },
3405 + ])("titles a Claude thread after its request, not command markup: $title", ({ first, title }) => {
3406 + const thread = AgentSessionScanner.parseAgentSessionTranscript({
3407 + contents: [first, "Plan the release"]
3408 + .map((content) =>
3409 + JSON.stringify({ type: "user", sessionId: "claude-session", message: { content } }),
3410 + )
3411 + .join("\n"),
3412 + source: "claudeAgent",
3413 + providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3414 + fallbackSessionId: "fallback",
3415 + lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3416 + });
3417 +
3418 + expect(thread?.title).toBe(title);
3419 + });
3420 +
3421 it.each([199, 200])("keeps the canonical first prompt with %s later Codex messages", (count) => {
3422 const canonicalPrompt = "\n Keep the canonical prompt \n";
3423 const canonicalTimestamp = "2026-08-24T10:01:00.000Z";
@@ -3789,18 +3852,38 @@ describe("parseAgentSessionTranscript", () => {
3852 expect(thread?.title).toBe(prompt);
3853 });
3854
3792 - it("skips sessions without a visible user message", () => {
3855 + it.each([
3856 + {
3857 + name: "only an assistant reply",
3858 + records: [{ type: "assistant", message: { content: "Done" } }],
3859 + expected: null,
3860 + },
3861 + {
3862 + name: "only a bare command",
3863 + records: [{ type: "user", message: { content: "<command-name>/clear</command-name>" } }],
3864 + expected: null,
3865 + },
3866 + {
3867 + name: "a bare command the agent answered",
3868 + records: [
3869 + { type: "user", message: { content: "<command-name>/review</command-name>" } },
3870 + { type: "assistant", message: { content: "Found two issues" } },
3871 + ],
3872 + expected: { title: "/review", texts: ["/review", "Found two issues"] },
3873 + },
3874 + ])("imports a Claude session only if it got a request: $name", ({ records, expected }) => {
3875 const thread = AgentSessionScanner.parseAgentSessionTranscript({
3794 - contents: JSON.stringify({
3795 - type: "assistant",
3796 - message: { role: "assistant", content: "Done" },
3797 - }),
3876 + contents: records.map((record) => JSON.stringify(record)).join("\n"),
3877 source: "claudeAgent",
3878 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
3879 fallbackSessionId: "claude-session",
3880 lastActiveAtMs: Date.parse("2026-08-24T12:00:00.000Z"),
3881 });
3882
3804 - expect(thread).toBeNull();
3883 + expect(
3884 + thread === null
3885 + ? null
3886 + : { title: thread.title, texts: thread.messages.map((message) => message.text) },
3887 + ).toEqual(expected);
3888 });
3889 });
apps/server/src/project/AgentSessionScanner.ts
+71 -18
@@ -363,10 +363,12 @@ function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord)
363 const model = record.message?.model?.trim();
364 return {
365 sessionId: record.sessionId?.trim() || fields.sessionId,
366 - title: record.aiTitle?.trim() || fields.title,
366 + title: claudeTitle(record.aiTitle) ?? fields.title,
367 // Claude flushes the AI title after the user's rename; an empty rename clears it.
368 customTitle:
369 - record.customTitle === undefined ? fields.customTitle : record.customTitle.trim() || null,
369 + record.customTitle === undefined
370 + ? fields.customTitle
371 + : (claudeTitle(record.customTitle) ?? null),
372 // Claude uses this sentinel for local error responses. It is not a
373 // model ID that can be selected when the imported session resumes.
374 model: model && model !== "<synthetic>" ? model : fields.model,
@@ -404,6 +406,44 @@ function codexHistoryBase(records: ReadonlyArray<DecodedTranscriptRecord>) {
406 : undefined;
407 }
408
409 +// Claude Code records its own UI as user turns: slash commands, `!` shell runs and
410 +// their output, task notifications. Keep what the user typed, as they typed it.
411 +const CLAUDE_UI_OUTPUT =
412 + /^(?:<(?:task-notification|local-command-stdout|local-command-stderr|local-command-caveat|bash-stdout|bash-stderr)>|\[Request interrupted by user(?: for tool use)?\]$)/;
413 +
414 +/**
415 + * A slash command as typed. Its arguments may name the thread; a bare command
416 + * leaves that to a later prompt. Null for any other text.
417 + */
418 +function claudeCommand(text: string): { readonly text: string; readonly titleText: string } | null {
419 + if (!/^<command-(?:name|message)>/.test(text)) return null;
420 + const name =
421 + /<command-name>([^<]*)<\/command-name>/.exec(text)?.[1]?.trim() ||
422 + `/${/<command-message>([^<]*)<\/command-message>/.exec(text)?.[1]?.trim() ?? ""}`;
423 + const args = /<command-args>([\s\S]*?)<\/command-args>/.exec(text)?.[1]?.trim() ?? "";
424 + return { text: args.length === 0 ? name : `${name} ${args}`, titleText: args };
425 +}
426 +
427 +/** What a Claude user turn shows the user typed, and the part of it that may name the thread. */
428 +function claudeUserText(text: string): { readonly text: string; readonly titleText: string } {
429 + if (CLAUDE_UI_OUTPUT.test(text)) return { text: "", titleText: "" };
430 + const shellInput = /^<bash-input>([\s\S]*)<\/bash-input>$/.exec(text)?.[1];
431 + if (shellInput !== undefined) return { text: `!${shellInput}`, titleText: "" };
432 + return claudeCommand(text) ?? { text, titleText: text };
433 +}
434 +
435 +function claudeVisibleText(record: DecodedTranscriptRecord) {
436 + const text = extractText(record.message?.content);
437 + return record.type === "user" ? claudeUserText(text) : { text, titleText: text };
438 +}
439 +
440 +/** Saved titles can be the raw markup of a user turn, such as the command that opened the session. */
441 +function claudeTitle(title: string | undefined): string | undefined {
442 + const trimmed = title?.trim();
443 + if (!trimmed) return undefined;
444 + return claudeUserText(trimmed).text === trimmed ? trimmed : undefined;
445 +}
446 +
447 // Agent-started sessions wrap the prompt in a `<wake reason=… current-time=…>`
448 // envelope; title them after the prompt inside it.
449 const WAKE_ENVELOPE = /^\s*<wake(?:\s[^>]*)?>([\s\S]*?)(?:<\/wake>|$)/;
@@ -487,6 +527,9 @@ function parseAgentSessionRecords(
527 : (claudeFields.title ?? null);
528 let model = claudeFields.model ?? null;
529 let derivedTitle: string | undefined;
530 + // Names a session whose only request was a bare command, such as `/review`.
531 + let bareCommandTitle: string | undefined;
532 + let hasAssistantMessage = false;
533 let hasCodexSessionId = false;
534 const messages: Array<AgentSessionThreadMessage & { readonly codexResponseUser: boolean }> = [];
535 let firstUserMessage:
@@ -548,13 +591,16 @@ function parseAgentSessionRecords(
591 let conversationMessageCount = 0;
592 const retainMessage = (
593 message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
594 + titleText = message.text,
595 ) => {
596 if (firstUserMessage === undefined && message.role === "user") {
597 firstUserMessage = message;
598 }
599 if (derivedTitle === undefined && message.role === "user") {
556 - derivedTitle = deriveTitle(input.source, message.text);
600 + derivedTitle = deriveTitle(input.source, titleText);
601 + bareCommandTitle ??= deriveTitle(input.source, message.text);
602 }
603 + hasAssistantMessage ||= message.role === "assistant";
604 conversationMessageCount += 1;
605 messages.push(message);
606 if (messages.length > MAX_IMPORTED_MESSAGES) messages.shift();
@@ -594,14 +640,17 @@ function parseAgentSessionRecords(
640 if (input.source === "claudeAgent") {
641 if (isHiddenClaudeRecord(record)) continue;
642 if (record.type !== "user" && record.type !== "assistant") continue;
597 - const text = extractText(record.message?.content);
643 + const { text, titleText } = claudeVisibleText(record);
644 if (text.length === 0) continue;
599 - retainMessage({
600 - role: record.type,
601 - text,
602 - createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
603 - codexResponseUser: false,
604 - });
645 + retainMessage(
646 + {
647 + role: record.type,
648 + text,
649 + createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
650 + codexResponseUser: false,
651 + },
652 + titleText,
653 + );
654 continue;
655 }
656
@@ -667,7 +716,14 @@ function parseAgentSessionRecords(
716 const visibleMessages = messages.map(
717 ({ codexResponseUser: _codexResponseUser, ...message }) => message,
718 );
670 - if (providerSessionId.trim().length === 0 || firstUserMessage === undefined) return null;
719 + if (
720 + providerSessionId.trim().length === 0 ||
721 + firstUserMessage === undefined ||
722 + // A Claude session of bare commands such as `/clear` that no reply followed did nothing.
723 + (input.source === "claudeAgent" && derivedTitle === undefined && !hasAssistantMessage)
724 + ) {
725 + return null;
726 + }
727 const firstUserMessageRetained = messages.includes(firstUserMessage);
728 const { codexResponseUser: _codexResponseUser, ...visibleFirstUserMessage } = firstUserMessage;
729 const retainedMessages = firstUserMessageRetained
@@ -678,7 +734,8 @@ function parseAgentSessionRecords(
734 source: input.source,
735 providerInstanceId: input.providerInstanceId,
736 providerSessionId,
681 - title: claudeFields.customTitle ?? title ?? derivedTitle ?? "Imported thread",
737 + title:
738 + claudeFields.customTitle ?? title ?? derivedTitle ?? bareCommandTitle ?? "Imported thread",
739 model,
740 createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
741 updatedAt: fallbackTimestamp,
@@ -702,12 +759,8 @@ function shouldRetainDecodedRecord(
759 if (isHiddenClaudeRecord(record) || (record.type !== "user" && record.type !== "assistant")) {
760 return false;
761 }
705 - const content = record.message?.content;
706 - return typeof content === "string"
707 - ? content.trim().length > 0
708 - : (content?.some(
709 - (block) => isTextContentBlock(block) && (block.text?.trim().length ?? 0) > 0,
710 - ) ?? false);
762 + // Same rule as the parser, so Claude Code's own output never takes a history window slot.
763 + return claudeVisibleText(record).text.length > 0;
764 }
765 if (extractDecodedCwd(record) !== null) return true;
766 return (
docs/user/welcome-page.md
+5 -2
@@ -95,8 +95,11 @@ newest remaining visible user and assistant messages, with 200 messages total.
95 It omits tool activity and attachments. For Codex, it omits generated setup
96 context only when a canonical user event and a valid shared turn ID identify the
97 same user turn. Ambiguous legacy or response-only context stays in the imported
98 -conversation so T3 Code does not remove user text. It reads one conversation at
99 -a time and skips files larger than 4 GiB. It also skips a conversation when the
98 +conversation so T3 Code does not remove user text. For Claude, slash commands
99 +and `!` shell commands appear as you typed them; their output, background task
100 +notifications and interruption markers are left out, and a conversation that
101 +only ran commands such as `/clear`, with no reply, is skipped. It reads one
102 +conversation at a time and skips files larger than 4 GiB. It also skips a conversation when the
103 message text and metadata it keeps need more than 32 MiB of memory. Tool output
104 does not count toward that limit. It skips a conversation with more than 100,000
105 records every time, so opening the page again does not import it. It ignores