Skip to content
109 changes: 109 additions & 0 deletions apps/server/src/project/AgentSessionScanner.claudeShell.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";

import * as ServerConfig from "../config.ts";
import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
import * as ServerSettings from "../serverSettings.ts";
import * as AgentSessionScanner from "./AgentSessionScanner.ts";

it.layer(NodeServices.layer)("Claude shell history", (it) => {
it.effect.each([
{
name: "a leading shell command followed by a prompt",
messages: ["<bash-input>git status</bash-input>", "Fix the login bug"],
title: "Fix the login bug",
omittedMessageCount: 0,
},
{
name: "a prompt outside the retained history after an opening shell command",
messages: [
"<bash-input>pwd</bash-input>",
"Fix the login bug",
...Array.from({ length: 200 }, () => "<command-name>/clear</command-name>"),
],
title: "Fix the login bug",
omittedMessageCount: 2,
},
{
name: "a shell command outside the retained history",
messages: [
"<command-name>/clear</command-name>",
"<bash-input>pwd</bash-input>",
...Array.from({ length: 200 }, () => "<command-name>/clear</command-name>"),
],
title: "!pwd",
omittedMessageCount: 2,
},
])("imports sessions with $name", ({ messages, title, omittedMessageCount }) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-shell-" });
const workspace = path.join(root, "workspace");
const claudeHome = path.join(root, "claude");
const transcripts = path.join(claudeHome, "projects", "-slug");
yield* fs.makeDirectory(workspace);
yield* fs.makeDirectory(transcripts, { recursive: true });
const file = path.join(transcripts, "shell-session.jsonl");
yield* fs.writeFileString(
file,
messages
.map((content) =>
JSON.stringify({
type: "user",
cwd: workspace,
sessionId: "shell-session",
message: { role: "user", content },
}),
)
.join("\n"),
);
const now = Date.parse("2026-08-24T12:00:00.000Z");
yield* TestClock.setTime(now);
const modifiedAtSeconds = now / 1000 - 60;
yield* fs.utimes(file, modifiedAtSeconds, modifiedAtSeconds);

const [result] = yield* AgentSessionScanner.AgentSessionScanner.use((scanner) =>
scanner.recentThreads(workspace).pipe(Stream.runCollect),
).pipe(
Effect.provide(
AgentSessionScanner.layer.pipe(
Layer.provide([
ServerConfig.layerTest(root, { prefix: "t3code-claude-shell-config-" }),
ServerSettings.layerTest({
providerInstances: {
[ProviderInstanceId.make("claudeAgent")]: {
driver: ProviderDriverKind.make("claudeAgent"),
config: { homePath: claudeHome },
},
[ProviderInstanceId.make("codex")]: {
driver: ProviderDriverKind.make("codex"),
enabled: false,
},
[ProviderInstanceId.make("pi")]: {
driver: ProviderDriverKind.make("pi"),
enabled: false,
},
},
}),
Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }),
Layer.mock(ProviderSessionRuntime.ProviderSessionRuntimeRepository)({
list: () => Effect.succeed([]),
}),
]),
),
),
);

expect(result).toMatchObject({ _tag: "Importable", thread: { title, omittedMessageCount } });
}),
);
});
14 changes: 14 additions & 0 deletions apps/server/src/project/AgentSessionScanner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4222,6 +4222,20 @@ describe("parseAgentSessionTranscript", () => {
records: [{ type: "user", message: { content: "<command-name>/clear</command-name>" } }],
expected: null,
},
{
name: "a shell command with output and no model reply",
records: [
{ type: "user", message: { role: "user", content: "<bash-input>pwd</bash-input>" } },
{
type: "user",
message: {
role: "user",
content: "<bash-stdout>/home/me/project</bash-stdout><bash-stderr></bash-stderr>",
},
},
],
expected: { title: "!pwd", texts: ["!pwd"] },
},
{
name: "a bare command the agent answered",
records: [
Expand Down
67 changes: 47 additions & 20 deletions apps/server/src/project/AgentSessionScanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -361,13 +361,17 @@ interface ClaudeFields {
readonly title: string | undefined;
readonly customTitle: string | null;
readonly model: string | undefined;
readonly promptTitle: string | undefined;
readonly shellCommandTitle: string | undefined;
}

const emptyClaudeFields: ClaudeFields = {
sessionId: undefined,
title: undefined,
customTitle: null,
model: undefined,
promptTitle: undefined,
shellCommandTitle: undefined,
};

// Claude Code's model name for its own local errors, such as "Invalid API key".
Expand All @@ -376,6 +380,11 @@ const CLAUDE_SYNTHETIC_MODEL = "<synthetic>";
function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord): ClaudeFields {
if (isHiddenClaudeRecord(record)) return fields;
const model = record.message?.model?.trim();
const userText =
record.type === "user" &&
(fields.promptTitle === undefined || fields.shellCommandTitle === undefined)
? claudeUserText(extractText(record.message?.content))
: undefined;
return {
sessionId: record.sessionId?.trim() || fields.sessionId,
title: claudeTitle(record.aiTitle) ?? fields.title,
Expand All @@ -386,6 +395,11 @@ function foldClaudeFields(fields: ClaudeFields, record: DecodedTranscriptRecord)
: (claudeTitle(record.customTitle) ?? null),
// Not a model ID that can be selected when the imported session resumes.
model: model && model !== CLAUDE_SYNTHETIC_MODEL ? model : fields.model,
promptTitle:
fields.promptTitle ?? (userText ? deriveTitle("claudeAgent", userText.titleText) : undefined),
shellCommandTitle:
fields.shellCommandTitle ??
(userText?.isShellCommand ? deriveTitle("claudeAgent", userText.text) : undefined),
};
}

Expand Down Expand Up @@ -439,16 +453,22 @@ function claudeCommand(text: string): { readonly text: string; readonly titleTex
}

/** What a Claude user turn shows the user typed, and the part of it that may name the thread. */
function claudeUserText(text: string): { readonly text: string; readonly titleText: string } {
function claudeUserText(text: string): {
readonly text: string;
readonly titleText: string;
readonly isShellCommand?: boolean;
} {
if (CLAUDE_UI_OUTPUT.test(text)) return { text: "", titleText: "" };
const shellInput = /^<bash-input>([\s\S]*)<\/bash-input>$/.exec(text)?.[1];
if (shellInput !== undefined) return { text: `!${shellInput}`, titleText: "" };
if (shellInput !== undefined) {
return { text: `!${shellInput}`, titleText: "", isShellCommand: shellInput.trim().length > 0 };
}
return claudeCommand(text) ?? { text, titleText: text };
}

function claudeVisibleText(record: DecodedTranscriptRecord) {
const text = extractText(record.message?.content);
return record.type === "user" ? claudeUserText(text) : { text, titleText: text };
return record.type === "user" ? claudeUserText(text).text : text;
}

/** Saved titles can be the raw markup of a user turn, such as the command that opened the session. */
Expand Down Expand Up @@ -541,7 +561,7 @@ function parseAgentSessionRecords(
? records.findLast((record) => record.type === "session_info")?.name?.trim() || null
: (claudeFields.title ?? null);
let model = claudeFields.model ?? null;
let derivedTitle: string | undefined;
let derivedTitle = claudeFields.promptTitle;
// Names a session whose only request was a bare command, such as `/review`.
let bareCommandTitle: string | undefined;
let hasAssistantMessage = false;
Expand Down Expand Up @@ -608,14 +628,16 @@ function parseAgentSessionRecords(
let conversationMessageCount = 0;
const retainMessage = (
message: AgentSessionThreadMessage & { readonly codexResponseUser: boolean },
titleText = message.text,
) => {
if (firstUserMessage === undefined && message.role === "user") {
firstUserMessage = message;
}
if (derivedTitle === undefined && message.role === "user") {
derivedTitle = deriveTitle(input.source, titleText);
bareCommandTitle ??= deriveTitle(input.source, message.text);
if (input.source === "claudeAgent") {
bareCommandTitle ??= deriveTitle(input.source, message.text);
} else {
derivedTitle = deriveTitle(input.source, message.text);
}
}
hasAssistantMessage ||= message.role === "assistant";
conversationMessageCount += 1;
Expand Down Expand Up @@ -657,22 +679,19 @@ function parseAgentSessionRecords(
if (input.source === "claudeAgent") {
if (isHiddenClaudeRecord(record)) continue;
if (record.type !== "user" && record.type !== "assistant") continue;
const { text, titleText } = claudeVisibleText(record);
const text = claudeVisibleText(record);
if (text.length === 0) continue;
if (record.type === "assistant") {
if (record.message?.model?.trim() === CLAUDE_SYNTHETIC_MODEL)
hasClaudeSyntheticReply = true;
else hasClaudeModelReply = true;
}
retainMessage(
{
role: record.type,
text,
createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
codexResponseUser: false,
},
titleText,
);
retainMessage({
role: record.type,
text,
createdAt: normalizeTimestamp(record.timestamp, fallbackTimestamp),
codexResponseUser: false,
});
continue;
}

Expand Down Expand Up @@ -742,7 +761,10 @@ function parseAgentSessionRecords(
providerSessionId.trim().length === 0 ||
firstUserMessage === undefined ||
// A Claude session of bare commands such as `/clear` that no reply followed did nothing.
(input.source === "claudeAgent" && derivedTitle === undefined && !hasAssistantMessage) ||
(input.source === "claudeAgent" &&
derivedTitle === undefined &&
claudeFields.shellCommandTitle === undefined &&
!hasAssistantMessage) ||
// Nor did one whose only replies are Claude Code's own errors.
(input.source === "claudeAgent" &&
droppedMessageCount === 0 &&
Expand All @@ -762,7 +784,12 @@ function parseAgentSessionRecords(
providerInstanceId: input.providerInstanceId,
providerSessionId,
title:
claudeFields.customTitle ?? title ?? derivedTitle ?? bareCommandTitle ?? "Imported thread",
claudeFields.customTitle ??
title ??
derivedTitle ??
claudeFields.shellCommandTitle ??
bareCommandTitle ??
"Imported thread",
model,
createdAt: retainedMessages[0]?.createdAt ?? fallbackTimestamp,
updatedAt: fallbackTimestamp,
Expand All @@ -787,7 +814,7 @@ function shouldRetainDecodedRecord(
return false;
}
// Same rule as the parser, so Claude Code's own output never takes a history window slot.
return claudeVisibleText(record).text.length > 0;
return claudeVisibleText(record).length > 0;
}
if (extractDecodedCwd(record) !== null) return true;
return (
Expand Down
Loading