Skip to content

Commit 03ee8e1

Browse files
dominikzabcikclaude
andcommitted
fix(server): import sessions from linked worktrees into their worktree
Claude, Codex and Pi sessions that ran in a linked git worktree of a normal checkout were never offered for import. The scan dropped the worktree, and importing the main checkout only took sessions whose cwd was the checkout itself. Users who keep one worktree per task lost all of those conversations. The scan now counts a linked worktree toward its main checkout. Importing that project reads its worktrees from `git worktree list` and binds each session from one of them to that worktree and its current branch, so the thread resumes there instead of in the main checkout. Only a main checkout claims worktrees, so a project that is itself a linked worktree, a subdirectory or a bare repository never takes its siblings' sessions. Detached, missing and T3-managed worktrees are skipped, and Git before 2.36 falls back to the line format. State-dir exclusion also matches real paths, because git reports them (`/private/var` on macOS, a symlinked T3 home). The import ledger keeps the project root as its cwd, so the next import still recognises worktree threads as already imported. Claude Opus 5.5 in Claude Code. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 6647b0a commit 03ee8e1

5 files changed

Lines changed: 326 additions & 55 deletions

File tree

‎apps/server/src/project/AgentSessionImporter.test.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { expect, it } from "@effect/vitest";
22
import {
3+
type AgentSessionImportSource,
34
type AgentSessionSource,
45
type ServerSettingsError,
56
EventId,
@@ -82,6 +83,7 @@ function candidate(
8283
{ role: "user" as const, text: "Fix it", createdAt: timestamp },
8384
{ role: "assistant" as const, text: "Fixed", createdAt: timestamp },
8485
],
86+
worktree: null as AgentSessionScanner.AgentSessionThread["worktree"],
8587
},
8688
} satisfies AgentSessionScanner.AgentSessionRecentThread;
8789
}
@@ -181,6 +183,7 @@ const makeImporter = Effect.fn(function* (
181183
const events = yield* EventStore.EventStoreV2;
182184
const projections = yield* ProjectionStore.ProjectionStoreV2;
183185
const published: Array<ApplicationStoredEvent> = [];
186+
const completedSources: Array<ReadonlyArray<AgentSessionImportSource>> = [];
184187
const withTransaction: typeof sql.withTransaction = (effect) =>
185188
beforeTransaction.pipe(Effect.andThen(sql.withTransaction(effect)));
186189
const importSql = new Proxy(sql, {
@@ -218,7 +221,10 @@ const makeImporter = Effect.fn(function* (
218221
yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository,
219222
),
220223
Layer.mock(AgentSessionScanner.AgentSessionScanner)({
221-
recentThreads: () => Stream.fromIterable(candidates),
224+
recentThreads: (_workspaceRoot, completed = []) => {
225+
completedSources.push(completed);
226+
return Stream.fromIterable(candidates);
227+
},
222228
}),
223229
Layer.mock(ProjectService.ProjectService)({
224230
getById: () =>
@@ -248,7 +254,7 @@ const makeImporter = Effect.fn(function* (
248254
),
249255
);
250256
const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter);
251-
return { run: importer.importRecentAgentThreads({ projectId }), published };
257+
return { run: importer.importRecentAgentThreads({ projectId }), published, completedSources };
252258
});
253259

254260
it.effect(
@@ -275,6 +281,8 @@ it.effect(
275281
const before = yield* Effect.forEach(owners, (id) =>
276282
projections.getThreadRecords(id, ["providerThreads"]),
277283
);
284+
const inWorktree = candidate(CODEX_MODEL_SELECTION, "in-worktree");
285+
inWorktree.thread.worktree = { path: "/workspace/project-worktrees/swc", branch: "swc" };
278286
const otherInstance = candidate(
279287
{ ...CLAUDE_MODEL_SELECTION, instanceId: ProviderInstanceId.make("claude-other") },
280288
archived.source.providerSessionId,
@@ -291,9 +299,10 @@ it.effect(
291299
otherInstance,
292300
unowned,
293301
unownedPi,
302+
inWorktree,
294303
]);
295304

296-
expect(yield* importer.run).toEqual({ importedCount: 3, skippedCount: 0 });
305+
expect(yield* importer.run).toEqual({ importedCount: 4, skippedCount: 0 });
297306
for (const source of [active, archived, deleted, ownedPi]) {
298307
const threadId = importId(source);
299308
expect(yield* Effect.option(projections.getThread(threadId))).toEqual(Option.none());
@@ -311,8 +320,15 @@ it.effect(
311320
"event" in stored ? [stored.event.threadId] : [],
312321
),
313322
),
314-
).toEqual(new Set([importId(otherInstance), importId(unowned), importId(unownedPi)]));
315-
for (const source of [otherInstance, unowned, unownedPi]) {
323+
).toEqual(
324+
new Set([
325+
importId(otherInstance),
326+
importId(unowned),
327+
importId(unownedPi),
328+
importId(inWorktree),
329+
]),
330+
);
331+
for (const source of [otherInstance, unowned, unownedPi, inWorktree]) {
316332
const threadId = importId(source);
317333
const records = yield* projections.getThreadRecords(threadId, [
318334
"messages",
@@ -336,15 +352,22 @@ it.effect(
336352
expect(records.thread.historyOrigin).toBe("v1_import");
337353
expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
338354
expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source));
355+
expect(records.thread).toMatchObject({
356+
branch: source.thread.worktree?.branch ?? null,
357+
worktreePath: source.thread.worktree?.path ?? null,
358+
});
339359
expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
340360
providerInstanceId: source.source.providerInstanceId,
341361
resumeCursor:
342362
source.source.provider === "claudeAgent"
343363
? { threadId, resume: source.source.providerSessionId }
344364
: { threadId: nativeId(source) },
345-
runtimePayload: { importedTranscripts: [source.source] },
365+
runtimePayload: { cwd: "/workspace/project", importedTranscripts: [source.source] },
346366
});
347367
}
368+
// Worktree threads count as this project's imports, so the next run does not reread them.
369+
yield* importer.run;
370+
expect(importer.completedSources[1]).toContainEqual(inWorktree.source);
348371
}).pipe(Effect.scoped, Effect.provide(persistence)),
349372
);
350373

‎apps/server/src/project/AgentSessionImporter.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -286,6 +286,7 @@ const make = Effect.gen(function* () {
286286
thread.source === "claudeAgent"
287287
? { threadId, resume: thread.providerSessionId }
288288
: { threadId: nativeThreadId },
289+
// Marks the import as this project's, even when the thread runs in a worktree.
289290
runtimePayload: { cwd: project.workspaceRoot },
290291
},
291292
{ onConflict: "ignore" },
@@ -325,8 +326,8 @@ const make = Effect.gen(function* () {
325326
modelSelection: { instanceId: thread.providerInstanceId, model },
326327
runtimeMode,
327328
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
328-
branch: null,
329-
worktreePath: null,
329+
branch: thread.worktree?.branch ?? null,
330+
worktreePath: thread.worktree?.path ?? null,
330331
linkedPullRequest: null,
331332
branchPullRequest: null,
332333
activeProviderThreadId: providerThreadId,

‎apps/server/src/project/AgentSessionScanner.test.ts‎

Lines changed: 126 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -822,7 +822,7 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
822822
}),
823823
);
824824

825-
it.effect("skips linked git worktrees and reports the origin of real checkouts", () =>
825+
it.effect("folds linked git worktrees into their checkout and reports real origins", () =>
826826
Effect.gen(function* () {
827827
const path = yield* Path.Path;
828828
const fileSystem = yield* FileSystem.FileSystem;
@@ -870,20 +870,26 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
870870
const result = yield* runScan({ claudeHomePath, codexHomePath });
871871

872872
expect(
873-
result.candidates.map((candidate) => ({ path: candidate.path, git: candidate.git })),
873+
result.candidates.map((candidate) => ({
874+
path: candidate.path,
875+
git: candidate.git,
876+
threadCount: candidate.threadCount,
877+
})),
874878
).toEqual([
875879
{
876880
path: submodule,
877881
git: {
878882
remoteKey: "gitlab.com/pingdotgg/libs/vendor",
879883
repository: "pingdotgg/libs/vendor",
880884
},
885+
threadCount: 1,
881886
},
882-
{ path: noRemote, git: { remoteKey: null, repository: null } },
883-
{ path: plain, git: null },
887+
{ path: noRemote, git: { remoteKey: null, repository: null }, threadCount: 1 },
888+
{ path: plain, git: null, threadCount: 1 },
884889
{
885890
path: repo,
886891
git: { remoteKey: "github.com/pingdotgg/t3code", repository: "pingdotgg/t3code" },
892+
threadCount: 2,
887893
},
888894
]);
889895
}),
@@ -993,13 +999,20 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
993999
yield* fileSystem.makeDirectory(worktreeCwd, { recursive: true });
9941000
const symlinkCwd = path.join(linkParent, "innocent-project");
9951001
yield* fileSystem.symlink(worktreeCwd, symlinkCwd);
1002+
// The server may know its state dir only by a symlinked path.
1003+
const configBaseDirAlias = path.join(linkParent, "state");
1004+
yield* fileSystem.symlink(configBaseDir, configBaseDirAlias);
9961005
yield* writeTranscript({
9971006
filePath: path.join(claudeHomePath, "projects", "-slug", "a.jsonl"),
9981007
contents: claudeSessionLine(symlinkCwd),
9991008
mtimeMs: Date.parse("2026-01-01T00:00:00.000Z"),
10001009
});
10011010

1002-
const result = yield* runScan({ claudeHomePath, codexHomePath, configBaseDir });
1011+
const result = yield* runScan({
1012+
claudeHomePath,
1013+
codexHomePath,
1014+
configBaseDir: configBaseDirAlias,
1015+
});
10031016

10041017
expect(result.candidates).toEqual([]);
10051018
}),
@@ -1090,6 +1103,114 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
10901103
});
10911104

10921105
describe("recentThreads", () => {
1106+
it.effect("binds sessions from the root's linked worktrees to that worktree and branch", () =>
1107+
Effect.gen(function* () {
1108+
const path = yield* Path.Path;
1109+
const fileSystem = yield* FileSystem.FileSystem;
1110+
const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1111+
yield* TestClock.setTime(nowMs);
1112+
const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1113+
const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1114+
const configBaseDir = yield* makeTempDir("t3code-scanner-base-");
1115+
const repo = yield* makeTempDir("t3code-workspace-repo-");
1116+
// Git reports real paths; `/var` is a symlink on macOS.
1117+
const worktrees = yield* fileSystem.realPath(
1118+
yield* makeTempDir("t3code-workspace-worktrees-"),
1119+
);
1120+
const git = (...args: ReadonlyArray<string>) =>
1121+
NodeChildProcess.execFileSync("git", ["-C", repo, ...args], { stdio: "ignore" });
1122+
git("init", "-q", "-b", "main");
1123+
git(
1124+
"-c",
1125+
"user.email=t@t",
1126+
"-c",
1127+
"user.name=t",
1128+
"commit",
1129+
"-q",
1130+
"--allow-empty",
1131+
"-m",
1132+
"i",
1133+
);
1134+
const feature = path.join(worktrees, "feature");
1135+
const detached = path.join(worktrees, "detached");
1136+
const pruned = path.join(worktrees, "pruned");
1137+
const locked = path.join(worktrees, "locked");
1138+
const switched = path.join(worktrees, "switched");
1139+
const managed = path.join(configBaseDir, "worktrees", "repo", "sandbox");
1140+
git("worktree", "add", "-q", "-b", "agent/feature", feature);
1141+
git("worktree", "add", "-q", "--detach", detached);
1142+
git("worktree", "add", "-q", "-b", "agent/pruned", pruned);
1143+
git("worktree", "add", "-q", "-b", "agent/locked", locked);
1144+
git("worktree", "lock", locked);
1145+
git("worktree", "add", "-q", "-b", "agent/before", switched);
1146+
NodeChildProcess.execFileSync("git", [
1147+
"-C",
1148+
switched,
1149+
"checkout",
1150+
"-q",
1151+
"-b",
1152+
"agent/after",
1153+
]);
1154+
git("worktree", "add", "-q", "-b", "t3/sandbox", managed);
1155+
yield* fileSystem.remove(pruned, { recursive: true });
1156+
yield* fileSystem.remove(locked, { recursive: true });
1157+
1158+
const sessions = { root: repo, feature, detached, pruned, locked, switched, managed };
1159+
for (const [index, [sessionId, cwd]] of Object.entries(sessions).entries()) {
1160+
yield* writeTranscript({
1161+
filePath: path.join(claudeHomePath, "projects", `-${sessionId}`, `${sessionId}.jsonl`),
1162+
contents: `${JSON.stringify({
1163+
type: "user",
1164+
cwd,
1165+
sessionId,
1166+
message: { role: "user", content: `Work in ${sessionId}` },
1167+
})}\n`,
1168+
mtimeMs: nowMs - (index + 1) * 1_000,
1169+
});
1170+
}
1171+
const bindings = (
1172+
workspaceRoot: string,
1173+
processRunner?: Layer.Layer<ProcessRunner.ProcessRunner>,
1174+
) =>
1175+
runRecentThreads({
1176+
claudeHomePath,
1177+
codexHomePath,
1178+
configBaseDir,
1179+
workspaceRoot,
1180+
...(processRunner === undefined ? {} : { processRunner }),
1181+
}).pipe(
1182+
Effect.map((threads) =>
1183+
threads.map(({ providerSessionId, worktree }) => ({ providerSessionId, worktree })),
1184+
),
1185+
);
1186+
1187+
const expected = [
1188+
{ providerSessionId: "root", worktree: null },
1189+
{ providerSessionId: "feature", worktree: { path: feature, branch: "agent/feature" } },
1190+
{ providerSessionId: "switched", worktree: { path: switched, branch: "agent/after" } },
1191+
];
1192+
expect(yield* bindings(repo)).toEqual(expected);
1193+
// Git before 2.36 rejects `worktree list -z`.
1194+
const legacyGit = Layer.effect(
1195+
ProcessRunner.ProcessRunner,
1196+
Effect.gen(function* () {
1197+
const runner = yield* ProcessRunner.ProcessRunner;
1198+
return ProcessRunner.ProcessRunner.of({
1199+
run: (input) =>
1200+
input.command === "git" && input.args.includes("-z")
1201+
? runner.run({ ...input, args: ["-C", repo, "worktree", "list", "--bogus"] })
1202+
: runner.run(input),
1203+
});
1204+
}),
1205+
).pipe(Layer.provide(ProcessRunner.layer), Layer.provide(NodeServices.layer));
1206+
expect(yield* bindings(repo, legacyGit)).toEqual(expected);
1207+
// A linked worktree as the root keeps only its own sessions.
1208+
expect(yield* bindings(feature)).toEqual([
1209+
{ providerSessionId: "feature", worktree: null },
1210+
]);
1211+
}),
1212+
);
1213+
10931214
it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () =>
10941215
Effect.gen(function* () {
10951216
const path = yield* Path.Path;

0 commit comments

Comments
 (0)