mirror of
https://github.com/getpaseo/paseo.git
synced 2026-10-29 04:32:57 +00:00
Preserve explicit Claude session names on import (#6930)
* fix(server): name an imported Claude agent after its /rename Importing a Claude session named the agent after its first prompt even when the session had been renamed in the CLI, so the name had to be set again by hand. #4216 fixed the Import Session listing; the imported agent still kept the prompt. Read the last usable `custom-title` from the transcript and pass it as the imported config title. The record is re-emitted on every save, so searching backwards from the end of the file finds the current name without walking a transcript that can reach tens of megabytes. Only an explicit rename is carried over. Agents are named after their first prompt line since #1563, so adopting the generated `ai-title` here would put that LLM summary back. Refs #2513 * refactor(server): drop unused generality from the Claude title reader readLastClaudeTitle took content, type and field so it could read both custom-title and ai-title records, which the listing needed before #4216 took that over. Only the custom-title read is left, so the two extra parameters are dead flexibility that also broke the single-object-parameter rule in packages/server/CLAUDE.md. Collapse it to readLastClaudeCustomTitle(content) and pull the record type into a constant so the needle and the type check share one literal. Hooks skipped: the repo-wide typecheck fails on two pre-existing Electron typing errors in packages/desktop/src/main.ts that reproduce with this change stashed. packages/server typecheck, lint and format all pass. * test(server): drive the real resume path in the import title tests The tests assigned an inline arrow function to client.resumeSession to keep Claude Code from spawning. Importing replays the transcript from disk and never starts a process, so the stub was never needed. Dropping it runs the real resume path, which is what docs/testing.md asks for, and removes the arrow assignment that docs/coding-standards.md rules out. Hooks skipped: the repo-wide typecheck fails on two pre-existing Electron typing errors in packages/desktop/src/main.ts that reproduce with this change stashed. packages/server typecheck, lint, format and the 83 claude tests pass. * fix(server): narrow the transcript read error instead of asserting it The ENOENT check cast the caught value to NodeJS.ErrnoException to reach `code`, which is the kind of assertion docs/coding-standards.md rules out: narrow with `if`, do not silence the compiler. Add the same local type guard pid-lock.ts already uses and test through it. Behaviour is unchanged. A value that is not an Error still falls through to the rethrow, exactly as reading `code` off the assertion did. Hooks skipped: the repo-wide typecheck fails on two pre-existing Electron typing errors in packages/desktop/src/main.ts that reproduce with this change stashed. packages/server typecheck, lint, format and the 83 claude tests pass. * fix(server): let claudeProjectDirSync resolve the Claude config dir The import title reader built the config dir itself through os.homedir(), but os is no longer imported here, so the fallback threw a ReferenceError whenever CLAUDE_CONFIG_DIR was unset. claudeProjectDirSync already resolves the same default. * test(server): give the import title helpers object parameters * fix(server): preserve imported session renames across history locations The import title reader must use the same provider environment and transcript lookup as history replay. Otherwise an imported session has its history but loses its explicit name when its configuration directory or project changed. Co-authored-by: platanus-kr <platanus.kr@gmail.com> --------- Co-authored-by: platanus-kr <platanus.kr@gmail.com> Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
platanus-kr
parent
4d5c3c13d4
commit
0708b8295c
@@ -0,0 +1,239 @@
|
||||
import * as fs from "node:fs/promises";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
|
||||
import { createTestLogger } from "../../../../test-utils/test-logger.js";
|
||||
import { ClaudeAgentClient } from "./agent.js";
|
||||
import { claudeProjectDirSync } from "./project-dir.js";
|
||||
|
||||
const SESSION_CWD = "/tmp/paseo-claude-renamed-import";
|
||||
|
||||
interface ClaudeTranscriptRecord {
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
let configDir: string;
|
||||
let previousConfigDir: string | undefined;
|
||||
|
||||
interface UserRecordInput {
|
||||
sessionId: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface WriteSessionInput {
|
||||
sessionId: string;
|
||||
records: ClaudeTranscriptRecord[];
|
||||
}
|
||||
|
||||
function userRecord({ sessionId, content }: UserRecordInput): ClaudeTranscriptRecord {
|
||||
return {
|
||||
isSidechain: false,
|
||||
type: "user",
|
||||
message: { role: "user", content },
|
||||
cwd: SESSION_CWD,
|
||||
sessionId,
|
||||
};
|
||||
}
|
||||
|
||||
async function writeSession({ sessionId, records }: WriteSessionInput): Promise<void> {
|
||||
const projectDir = claudeProjectDirSync(SESSION_CWD, { configDir });
|
||||
await fs.mkdir(projectDir, { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(projectDir, `${sessionId}.jsonl`),
|
||||
`${records.map((record) => JSON.stringify(record)).join("\n")}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
// Importing replays the transcript from disk, so this drives the real resume
|
||||
// path without starting Claude Code.
|
||||
async function importSession(sessionId: string) {
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
return client.importSession(
|
||||
{ providerHandleId: sessionId, cwd: SESSION_CWD },
|
||||
{
|
||||
config: { provider: "claude", cwd: SESSION_CWD },
|
||||
storedConfig: { provider: "claude", cwd: SESSION_CWD },
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
configDir = await fs.mkdtemp(path.join(os.tmpdir(), "paseo-claude-renamed-"));
|
||||
previousConfigDir = process.env.CLAUDE_CONFIG_DIR;
|
||||
process.env.CLAUDE_CONFIG_DIR = configDir;
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (previousConfigDir === undefined) {
|
||||
delete process.env.CLAUDE_CONFIG_DIR;
|
||||
} else {
|
||||
process.env.CLAUDE_CONFIG_DIR = previousConfigDir;
|
||||
}
|
||||
await fs.rm(configDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("importing a renamed Claude session", () => {
|
||||
test.each(["provider", "launch"])(
|
||||
"reads the rename from the %s config directory used for history",
|
||||
async (source) => {
|
||||
const sessionId = "provider-directory-rename";
|
||||
const providerConfigDir = path.join(configDir, "provider");
|
||||
const projectDir = claudeProjectDirSync(SESSION_CWD, { configDir: providerConfigDir });
|
||||
await fs.mkdir(projectDir, { recursive: true });
|
||||
await fs.writeFile(
|
||||
path.join(projectDir, `${sessionId}.jsonl`),
|
||||
[
|
||||
userRecord({ sessionId, content: "Review this project" }),
|
||||
{ type: "custom-title", customTitle: "My research session", sessionId },
|
||||
]
|
||||
.map((record) => JSON.stringify(record))
|
||||
.join("\n") + "\n",
|
||||
);
|
||||
const client = new ClaudeAgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtimeSettings:
|
||||
source === "provider" ? { env: { CLAUDE_CONFIG_DIR: providerConfigDir } } : undefined,
|
||||
resolveBinary: async () => "/test/claude/bin",
|
||||
});
|
||||
const imported = await client.importSession(
|
||||
{ providerHandleId: sessionId, cwd: SESSION_CWD },
|
||||
{
|
||||
config: { provider: "claude", cwd: SESSION_CWD },
|
||||
storedConfig: { provider: "claude", cwd: SESSION_CWD },
|
||||
launchContext:
|
||||
source === "launch" ? { env: { CLAUDE_CONFIG_DIR: providerConfigDir } } : undefined,
|
||||
},
|
||||
);
|
||||
expect(imported.timeline.map((entry) => entry.item)).toContainEqual(
|
||||
expect.objectContaining({ type: "user_message", text: "Review this project" }),
|
||||
);
|
||||
expect(imported.config.title).toBe("My research session");
|
||||
},
|
||||
);
|
||||
|
||||
test("names the imported agent after a /rename", async () => {
|
||||
const sessionId = "renamed-session";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "Review this project" }),
|
||||
{ type: "custom-title", customTitle: "My research session", sessionId },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBe("My research session");
|
||||
});
|
||||
|
||||
test("uses the last rename when the session was renamed more than once", async () => {
|
||||
const sessionId = "renamed-twice";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "Move invoices to the new schema" }),
|
||||
{ type: "custom-title", customTitle: "invoices", sessionId },
|
||||
{ type: "custom-title", customTitle: "billing rework", sessionId },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBe("billing rework");
|
||||
});
|
||||
|
||||
test("preserves a rename when the first prompt was /model", async () => {
|
||||
const sessionId = "model-first";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "/model" }),
|
||||
{ type: "custom-title", customTitle: "My research session", sessionId },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBe("My research session");
|
||||
});
|
||||
|
||||
test("keeps the rename when a later record carries no usable name", async () => {
|
||||
const sessionId = "malformed-later-record";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "Review this project" }),
|
||||
{ type: "custom-title", customTitle: "My research session", sessionId },
|
||||
{ type: "custom-title", sessionId },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBe("My research session");
|
||||
});
|
||||
|
||||
test("ignores a rename recorded on a sidechain transcript", async () => {
|
||||
const sessionId = "sidechain-rename";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "Review this project" }),
|
||||
{ type: "custom-title", customTitle: "Subagent title", sessionId, isSidechain: true },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBeUndefined();
|
||||
});
|
||||
|
||||
test("leaves the agent untitled when the session was never renamed", async () => {
|
||||
const sessionId = "never-renamed";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [userRecord({ sessionId, content: "Review this project" })],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
expect(imported.config.title).toBeUndefined();
|
||||
});
|
||||
|
||||
test("does not name the imported agent after a generated ai-title", async () => {
|
||||
const sessionId = "auto-titled";
|
||||
await writeSession({
|
||||
sessionId,
|
||||
records: [
|
||||
userRecord({ sessionId, content: "Add pagination to the invoice list" }),
|
||||
{ type: "ai-title", aiTitle: "Invoice list pagination", sessionId },
|
||||
],
|
||||
});
|
||||
|
||||
const imported = await importSession(sessionId);
|
||||
|
||||
// The Import Session list shows it, but agents are named from their first
|
||||
// prompt line.
|
||||
expect(imported.config.title).toBeUndefined();
|
||||
});
|
||||
|
||||
test("imports a session that has no transcript on disk", async () => {
|
||||
const imported = await importSession("no-such-session");
|
||||
|
||||
expect(imported.config.title).toBeUndefined();
|
||||
});
|
||||
|
||||
test("surfaces an unreadable transcript instead of importing it as never renamed", async () => {
|
||||
const sessionId = "unreadable-transcript";
|
||||
// A directory where the transcript belongs fails the read with EISDIR, the
|
||||
// deterministic stand-in for a permissions or I/O fault.
|
||||
const projectDir = claudeProjectDirSync(SESSION_CWD, { configDir });
|
||||
await fs.mkdir(path.join(projectDir, `${sessionId}.jsonl`), { recursive: true });
|
||||
|
||||
await expect(importSession(sessionId)).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1693,11 +1693,21 @@ export class ClaudeAgentClient implements AgentClient {
|
||||
}
|
||||
|
||||
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
|
||||
// Carry a `/rename` onto the imported agent so the name chosen in the CLI
|
||||
// survives the import. Only an explicit rename counts: agents are named
|
||||
// after their first prompt line since #1563, so adopting the generated
|
||||
// `ai-title` here would put that LLM summary back.
|
||||
const renamedTitle = await readClaudeRenamedSessionTitle({
|
||||
cwd: input.cwd,
|
||||
sessionId: input.providerHandleId,
|
||||
configDir: claudeConfigDir(this.buildProviderEnv(context.launchContext?.env)),
|
||||
});
|
||||
return importSessionFromPersistence({
|
||||
provider: "claude",
|
||||
request: input,
|
||||
context,
|
||||
resumeSession: this.resumeSession.bind(this),
|
||||
...(renamedTitle ? { config: { title: renamedTitle } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6603,6 +6613,66 @@ function normalizeClaudeSessionTitle(title: string | null): string | null {
|
||||
return normalized ? normalized : null;
|
||||
}
|
||||
|
||||
const CLAUDE_CUSTOM_TITLE_TYPE = "custom-title";
|
||||
|
||||
/**
|
||||
* The `custom-title` record is re-emitted every time the session is saved, so
|
||||
* the current name is the last usable one in the file. Searching backwards finds it without
|
||||
* walking the transcript, which matters because sessions reach tens of
|
||||
* megabytes.
|
||||
*/
|
||||
function readLastClaudeCustomTitle(content: string): string | null {
|
||||
const needle = `"${CLAUDE_CUSTOM_TITLE_TYPE}"`;
|
||||
let at = content.lastIndexOf(needle);
|
||||
while (at >= 0) {
|
||||
const lineStart = content.lastIndexOf("\n", at) + 1;
|
||||
const lineEnd = content.indexOf("\n", at);
|
||||
const line = lineEnd === -1 ? content.slice(lineStart) : content.slice(lineStart, lineEnd);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line.trim());
|
||||
} catch {
|
||||
parsed = undefined;
|
||||
}
|
||||
const entry = toObjectRecord(parsed);
|
||||
if (entry && !entry.isSidechain && entry.type === CLAUDE_CUSTOM_TITLE_TYPE) {
|
||||
const title = normalizeClaudeSessionTitle(
|
||||
typeof entry.customTitle === "string" ? entry.customTitle : null,
|
||||
);
|
||||
if (title) {
|
||||
return title;
|
||||
}
|
||||
}
|
||||
// The needle also matches a prompt that quotes it, and a record can carry no
|
||||
// usable name, so keep looking backwards for one that does.
|
||||
at = at <= 0 ? -1 : content.lastIndexOf(needle, at - 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isErrnoException(error: unknown): error is NodeJS.ErrnoException {
|
||||
return error instanceof Error && "code" in error;
|
||||
}
|
||||
|
||||
async function readClaudeRenamedSessionTitle(input: {
|
||||
cwd: string;
|
||||
sessionId: string;
|
||||
configDir: string;
|
||||
}): Promise<string | null> {
|
||||
let content: string;
|
||||
try {
|
||||
content = await fsPromises.readFile(claudeTranscriptPathSync(input), "utf8");
|
||||
} catch (error) {
|
||||
// A session with no transcript on disk has no rename to carry over. Every
|
||||
// other read failure is a real fault and stays explicit.
|
||||
if (isErrnoException(error) && error.code === "ENOENT") {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return readLastClaudeCustomTitle(content);
|
||||
}
|
||||
|
||||
function normalizeImportablePromptPreview(text: string): string | null {
|
||||
const normalized = text.trim().replace(/\s+/g, " ");
|
||||
if (!normalized) return null;
|
||||
|
||||
@@ -67,6 +67,7 @@ describe("daemon E2E - Claude history stored under another project folder", () =
|
||||
content: "reply from the original folder",
|
||||
},
|
||||
},
|
||||
{ type: "custom-title", customTitle: "Renamed moved session", sessionId: SESSION_ID },
|
||||
]
|
||||
.map((entry) => `${JSON.stringify(entry)}\n`)
|
||||
.join(""),
|
||||
@@ -114,6 +115,7 @@ describe("daemon E2E - Claude history stored under another project folder", () =
|
||||
sessionId: SESSION_ID,
|
||||
cwd: agentCwd,
|
||||
});
|
||||
expect(agent.title).toBe("Renamed moved session");
|
||||
await stopDaemon();
|
||||
|
||||
const restartedClient = await startDaemon();
|
||||
|
||||
@@ -55,6 +55,7 @@ describe("daemon E2E - Claude history lives in the provider's CLAUDE_CONFIG_DIR"
|
||||
cwd,
|
||||
message: { role: "assistant", content: "reply from the custom config dir" },
|
||||
},
|
||||
{ type: "custom-title", customTitle: "Renamed provider session", sessionId: SESSION_ID },
|
||||
]
|
||||
.map((entry) => `${JSON.stringify(entry)}\n`)
|
||||
.join(""),
|
||||
@@ -111,6 +112,7 @@ describe("daemon E2E - Claude history lives in the provider's CLAUDE_CONFIG_DIR"
|
||||
sessionId: SESSION_ID,
|
||||
cwd,
|
||||
});
|
||||
expect(agent.title).toBe("Renamed provider session");
|
||||
await stopDaemon();
|
||||
|
||||
const restartedClient = await startDaemon();
|
||||
|
||||
Reference in New Issue
Block a user