Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions apps/server/src/project/AgentSessionImporter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ function candidate(
{ role: "assistant" as const, text: "Fixed", createdAt: timestamp },
],
},
worktree: { path: "/workspace/project-feature", branch: "feature" },
} satisfies AgentSessionScanner.AgentSessionRecentThread;
}

Expand Down Expand Up @@ -334,6 +335,8 @@ it.effect(
expect(notices).toEqual([]);
}
expect(records.thread.historyOrigin).toBe("v1_import");
expect(records.thread.worktreePath).toBe("/workspace/project-feature");
expect(records.thread.branch).toBe("feature");
expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source));
expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
Expand Down
4 changes: 2 additions & 2 deletions apps/server/src/project/AgentSessionImporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,8 +325,8 @@ const make = Effect.gen(function* () {
modelSelection: { instanceId: thread.providerInstanceId, model },
runtimeMode,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
branch: null,
worktreePath: null,
branch: outcome.worktree?.branch ?? null,
worktreePath: outcome.worktree?.path ?? null,
linkedPullRequest: null,
branchPullRequest: null,
activeProviderThreadId: providerThreadId,
Expand Down
169 changes: 169 additions & 0 deletions apps/server/src/project/AgentSessionScanner.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
Expand Down Expand Up @@ -59,6 +60,8 @@ interface ScannerTestInput {
readonly importedWorkspaceRoots?: ReadonlyArray<string>;
readonly configBaseDir?: string;
readonly providerInstances?: ContractServerSettings["providerInstances"];
readonly worktreesDirectory?: string;
readonly previousWorktreesDirectories?: ReadonlyArray<string>;
readonly processRunner?: Layer.Layer<ProcessRunner.ProcessRunner>;
}

Expand All @@ -72,6 +75,8 @@ const layerScannerTest = (input: ScannerTestInput) =>
Layer.provide(
Layer.mergeAll(
ServerSettings.layerTest({
worktreesDirectory: input.worktreesDirectory ?? "",
previousWorktreesDirectories: input.previousWorktreesDirectories ?? [],
providerInstances: {
[ProviderInstanceId.make("claudeAgent")]: {
driver: ProviderDriverKind.make("claudeAgent"),
Expand Down Expand Up @@ -147,6 +152,27 @@ const writeTranscript = Effect.fn("AgentSessionScanner.test.writeTranscript")(fu
yield* fileSystem.utimes(input.filePath, seconds, seconds);
});

/** Lays out a linked worktree the way `git worktree add` does, without running git. */
const addLinkedWorktree = Effect.fn("AgentSessionScanner.test.addLinkedWorktree")(
function* (input: {
readonly commonGitDir: string;
readonly directory: string;
readonly branch: string;
}) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const gitDir = path.join(input.commonGitDir, "worktrees", input.branch);
yield* fileSystem.makeDirectory(gitDir, { recursive: true });
yield* fileSystem.makeDirectory(input.directory, { recursive: true });
yield* fileSystem.writeFileString(path.join(gitDir, "commondir"), "../..\n");
yield* fileSystem.writeFileString(
path.join(gitDir, "HEAD"),
`ref: refs/heads/${input.branch}\n`,
);
yield* fileSystem.writeFileString(path.join(input.directory, ".git"), `gitdir: ${gitDir}\n`);
},
);

const claudeSessionLine = (cwd: string) =>
`${JSON.stringify({ type: "user", cwd, sessionId: "s1" })}\n${JSON.stringify({ type: "assistant" })}\n`;

Expand Down Expand Up @@ -2105,6 +2131,149 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
}),
);

it.effect.each(["directory", "pointer", "unreadable-managed-directory"] as const)(
"imports only the project's linked worktrees with their branches when .git is a %s",
(layout) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
yield* TestClock.setTime(nowMs);
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
const repo = yield* makeTempDir("t3code-workspace-repo-");
const otherRepo = yield* makeTempDir("t3code-workspace-other-");
const commonGitDir =
layout !== "pointer"
? path.join(repo, ".git")
: yield* makeTempDir("t3code-separate-git-dir-");
if (layout === "pointer") {
yield* fileSystem.writeFileString(path.join(repo, ".git"), `gitdir: ${commonGitDir}\n`);
}

const worktree = path.join(repo, ".claude", "worktrees", "feature");
const externalWorktree = yield* makeTempDir("t3code-workspace-feature-");
const managedWorktree = path.join(configBaseDir, "worktrees", "repo", "managed");
const customDirectory = yield* makeTempDir("t3code-custom-worktrees-").pipe(
Effect.flatMap((directory) => fileSystem.realPath(directory)),
);
const previousDirectory = yield* makeTempDir("t3code-previous-worktrees-");
const customWorktree = path.join(customDirectory, "repo", "custom");
const previousWorktree = path.join(previousDirectory, "repo", "previous");
const otherWorktree = path.join(repo, "unrelated");
yield* addLinkedWorktree({ commonGitDir, directory: worktree, branch: "feature" });
yield* addLinkedWorktree({
commonGitDir,
directory: externalWorktree,
branch: "external",
});
yield* addLinkedWorktree({ commonGitDir, directory: managedWorktree, branch: "managed" });
yield* addLinkedWorktree({ commonGitDir, directory: customWorktree, branch: "custom" });
yield* addLinkedWorktree({
commonGitDir,
directory: previousWorktree,
branch: "previous",
});
yield* addLinkedWorktree({
commonGitDir: path.join(otherRepo, ".git"),
directory: otherWorktree,
branch: "elsewhere",
});

let worktreesDirectory = customDirectory;
const previousWorktreesDirectories = [previousDirectory, path.parse(repo).root];
const sessions = [
{ sessionId: "root-session", cwd: repo },
{ sessionId: "worktree-session", cwd: worktree },
{ sessionId: "external-session", cwd: externalWorktree },
{ sessionId: "managed-session", cwd: managedWorktree },
{ sessionId: "custom-session", cwd: customWorktree },
{ sessionId: "previous-session", cwd: previousWorktree },
{ sessionId: "other-session", cwd: otherWorktree },
];
if (symlinksSupported) {
const aliases = yield* makeTempDir("t3code-managed-aliases-");
for (const [name, directory, branch] of [
["default", path.join(configBaseDir, "worktrees"), "managed"],
["custom", customDirectory, "custom"],
["previous", previousDirectory, "previous"],
] as const) {
const alias = path.join(aliases, name);
yield* fileSystem.symlink(directory, alias);
sessions.push({
sessionId: `${name}-alias-session`,
cwd: path.join(alias, "repo", branch),
});
if (name === "custom" && layout !== "unreadable-managed-directory")
worktreesDirectory = alias;
if (name === "previous") previousWorktreesDirectories[0] = alias;
}
const rootAlias = path.join(aliases, "root");
yield* fileSystem.symlink(path.parse(repo).root, rootAlias);
previousWorktreesDirectories.push(rootAlias);
const escapedAlias = path.join(customDirectory, "external");
yield* fileSystem.symlink(externalWorktree, escapedAlias);
sessions.push({ sessionId: "managed-escape-session", cwd: escapedAlias });
}

for (const [index, session] of sessions.entries()) {
yield* writeTranscript({
filePath: path.join(claudeHomePath, "projects", session.sessionId, "session.jsonl"),
contents: `${JSON.stringify({
type: "user",
...session,
message: { role: "user", content: "Fix the project" },
})}\n`,
mtimeMs: nowMs - (index + 1) * 60 * 1000,
});
}

const outcomes = yield* runRecentThreadOutcomes({
claudeHomePath,
codexHomePath,
configBaseDir,
workspaceRoot: repo,
worktreesDirectory,
previousWorktreesDirectories,
}).pipe(
Effect.provideService(
FileSystem.FileSystem,
FileSystem.FileSystem.of({
...fileSystem,
realPath: (target) =>
layout === "unreadable-managed-directory" && target === worktreesDirectory
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
? Effect.fail(
new PlatformError.PlatformError(
new PlatformError.SystemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "realPath",
}),
),
)
: fileSystem.realPath(target),
}),
),
);

expect(
outcomes.flatMap((outcome) =>
outcome._tag === "Importable"
? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }]
: [],
),
).toEqual([
{ sessionId: "root-session", worktree: null },
{ sessionId: "worktree-session", worktree: { path: worktree, branch: "feature" } },
{
sessionId: "external-session",
worktree: { path: externalWorktree, branch: "external" },
},
]);
}),
);

it.effect("uses configured order when custom instances share a session home", () =>
Effect.gen(function* () {
const path = yield* Path.Path;
Expand Down
Loading
Loading