The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 17:15 UTC
fix(server): session import brings in the linked-worktree sessions the Welcome page counts (#36242)
Julius Marminge committed
Nov 13, 2026 at 10:10 UTC
2d5e0ae2bd60d27422596cbd3d5d84d569b0ad51
4 files changed
+195
-69
apps/server/src/project/AgentSessionImporter.test.ts
+8
-1
@@ -92,6 +92,7 @@ function candidate(
92
{ role: "assistant" as const, text: "Fixed", createdAt: timestamp },
93
],
94
},
95
+ worktree: null as { path: string; branch: string | null } | null,
96
} satisfies AgentSessionScanner.AgentSessionRecentThread;
97
}
98
@@ -304,6 +305,7 @@ it.effect(
305
);
306
const unowned = candidate(CODEX_MODEL_SELECTION, "unowned");
307
unowned.thread.omittedMessageCount = 1;
308
+ unowned.worktree = { path: "/workspace/project/.claude/worktrees/feat", branch: "feat" };
309
const unownedPi = candidate(PI_MODEL_SELECTION, "unowned-pi", "pi");
310
const importer = yield* makeImporter([
311
active,
@@ -356,6 +358,8 @@ it.effect(
358
expect(notices).toEqual([]);
359
}
360
expect(records.thread.historyOrigin).toBe("v1_import");
361
+ expect(records.thread.worktreePath).toBe(source.worktree?.path ?? null);
362
+ expect(records.thread.branch).toBe(source.worktree?.branch ?? null);
363
expect(records.thread.activeProviderThreadId).toBe(records.providerThreads[0]?.id);
364
expect(records.providerThreads[0]?.nativeThreadRef?.nativeId).toBe(nativeId(source));
365
expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId }))).toMatchObject({
@@ -364,7 +368,10 @@ it.effect(
368
source.source.provider === "claudeAgent"
369
? { threadId, resume: source.source.providerSessionId }
370
: { threadId: nativeId(source) },
367
- runtimePayload: { importedTranscripts: [source.source] },
371
+ runtimePayload: {
372
+ cwd: source.worktree?.path ?? "/workspace/project",
373
+ importedTranscripts: [source.source],
374
+ },
375
});
376
}
377
}).pipe(Effect.scoped, Effect.provide(persistence)),
apps/server/src/project/AgentSessionImporter.ts
+3
-3
@@ -309,7 +309,7 @@ const make = Effect.gen(function* () {
309
thread.source === "claudeAgent"
310
? { threadId, resume: thread.providerSessionId }
311
: { threadId: nativeThreadId },
312
- runtimePayload: { cwd: project.workspaceRoot },
312
+ runtimePayload: { cwd: outcome.worktree?.path ?? project.workspaceRoot },
313
},
314
{ onConflict: "ignore" },
315
);
@@ -362,8 +362,8 @@ const make = Effect.gen(function* () {
362
modelSelection: { instanceId: thread.providerInstanceId, model },
363
runtimeMode,
364
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
365
- branch: null,
366
- worktreePath: null,
365
+ branch: outcome.worktree?.branch ?? null,
366
+ worktreePath: outcome.worktree?.path ?? null,
367
linkedPullRequest: null,
368
branchPullRequest: null,
369
activeProviderThreadId: providerThreadId,
apps/server/src/project/AgentSessionScanner.test.ts
+64
@@ -1104,6 +1104,70 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => {
1104
}),
1105
);
1106
1107
+ it.effect("imports a checkout's sessions from the linked worktrees the scan counts", () =>
1108
+ Effect.gen(function* () {
1109
+ const path = yield* Path.Path;
1110
+ const fileSystem = yield* FileSystem.FileSystem;
1111
+ const nowMs = Date.parse("2026-08-24T12:00:00.000Z");
1112
+ yield* TestClock.setTime(nowMs);
1113
+ const claudeHomePath = yield* makeTempDir("t3code-claude-home-");
1114
+ const codexHomePath = yield* makeTempDir("t3code-codex-home-");
1115
+ const repo = yield* makeTempDir("t3code-workspace-repo-");
1116
+ yield* fileSystem.makeDirectory(path.join(repo, ".git"));
1117
+ yield* fileSystem.writeFileString(path.join(repo, ".git", "config"), "[core]\n");
1118
+ const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature");
1119
+ yield* fileSystem.makeDirectory(worktreeGitDir, { recursive: true });
1120
+ yield* fileSystem.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
1121
+ yield* fileSystem.writeFileString(
1122
+ path.join(worktreeGitDir, "HEAD"),
1123
+ "ref: refs/heads/feature\n",
1124
+ );
1125
+ const worktree = path.join(repo, ".claude", "worktrees", "feature");
1126
+ yield* fileSystem.makeDirectory(worktree, { recursive: true });
1127
+ yield* fileSystem.writeFileString(
1128
+ path.join(worktree, ".git"),
1129
+ `gitdir: ${worktreeGitDir}\n`,
1130
+ );
1131
+
1132
+ for (const [index, [cwd, sessionId]] of [
1133
+ [repo, "at-root"],
1134
+ [worktree, "in-worktree"],
1135
+ ].entries()) {
1136
+ yield* writeTranscript({
1137
+ filePath: path.join(claudeHomePath, "projects", `-slug-${index}`, `${sessionId}.jsonl`),
1138
+ contents: `${JSON.stringify({
1139
+ type: "user",
1140
+ cwd,
1141
+ sessionId,
1142
+ message: { role: "user", content: "Fix the project" },
1143
+ })}\n${JSON.stringify({
1144
+ type: "assistant",
1145
+ sessionId,
1146
+ message: { role: "assistant", content: [{ type: "text", text: "Done" }] },
1147
+ })}\n`,
1148
+ mtimeMs: nowMs - (index + 1) * 60 * 60 * 1000,
1149
+ });
1150
+ }
1151
+
1152
+ const input = { claudeHomePath, codexHomePath };
1153
+ const { candidates } = yield* runScan(input);
1154
+ expect(candidates.map(({ path, threadCount }) => ({ path, threadCount }))).toEqual([
1155
+ { path: repo, threadCount: 2 },
1156
+ ]);
1157
+ const outcomes = yield* runRecentThreadOutcomes({ ...input, workspaceRoot: repo });
1158
+ expect(
1159
+ outcomes.flatMap((outcome) =>
1160
+ outcome._tag === "Importable"
1161
+ ? [{ sessionId: outcome.thread.providerSessionId, worktree: outcome.worktree }]
1162
+ : [],
1163
+ ),
1164
+ ).toEqual([
1165
+ { sessionId: "at-root", worktree: null },
1166
+ { sessionId: "in-worktree", worktree: { path: worktree, branch: "feature" } },
1167
+ ]);
1168
+ }),
1169
+ );
1170
+
1171
it.effect("excludes sandboxes under the configured worktrees dir without .t3 in the path", () =>
1172
Effect.gen(function* () {
1173
const path = yield* Path.Path;
apps/server/src/project/AgentSessionScanner.ts
+120
-65
@@ -223,6 +223,8 @@ export type AgentSessionRecentThread =
223
readonly _tag: "Importable";
224
readonly thread: AgentSessionThread;
225
readonly source: AgentSessionImportSource;
226
+ /** The root's linked worktree the session ran in, or null when it ran in the root. */
227
+ readonly worktree: { readonly path: string; readonly branch: string | null } | null;
228
}
229
| { readonly _tag: "AlreadyImported"; readonly source: AgentSessionImportSource }
230
| { readonly _tag: "Duplicate"; readonly source: AgentSessionImportSource }
@@ -979,19 +981,24 @@ export const make = Effect.gen(function* () {
981
| { readonly _tag: "Repository"; readonly git: AgentSessionProjectGit | null }
982
| {
983
readonly _tag: "Worktree";
984
+ readonly gitDir: string;
985
readonly mainCheckout: string | null;
986
readonly git: AgentSessionProjectGit | null;
987
}
988
| { readonly _tag: "NotGit" };
989
const identities = new Map<string, GitIdentity>();
987
- const repositories: Array<{ directory: string; gitDir: string; linkedWorktree: boolean }> = [];
990
+ const repositories: Array<{
991
+ directory: string;
992
+ gitDir: string;
993
+ worktreeGitDir: string | null;
994
+ }> = [];
995
const pointers: Array<{ directory: string; gitPath: string }> = [];
996
for (const directory of directories) {
997
const gitPath = path.join(directory, ".git");
998
const gitStats = yield* statOption(gitPath);
999
if (Option.isNone(gitStats)) identities.set(directory, { _tag: "NotGit" });
1000
else if (gitStats.value.type === "Directory") {
994
- repositories.push({ directory, gitDir: gitPath, linkedWorktree: false });
1001
+ repositories.push({ directory, gitDir: gitPath, worktreeGitDir: null });
1002
} else pointers.push({ directory, gitPath });
1003
}
1004
@@ -1006,7 +1013,7 @@ export const make = Effect.gen(function* () {
1013
const gitDir = path.resolve(directory, target);
1014
if (/[\\/]worktrees[\\/][^\\/]+[\\/]?$/.test(gitDir)) {
1015
linkedWorktrees.push({ directory, gitDir });
1009
- } else repositories.push({ directory, gitDir, linkedWorktree: false });
1016
+ } else repositories.push({ directory, gitDir, worktreeGitDir: null });
1017
}
1018
1019
const commonDirTexts = yield* readGitFiles(
@@ -1015,19 +1022,19 @@ export const make = Effect.gen(function* () {
1022
for (const { directory, gitDir } of linkedWorktrees) {
1023
const commonDir = (commonDirTexts.get(path.join(gitDir, "commondir")) ?? "").trim();
1024
if (commonDir.length === 0) {
1018
- identities.set(directory, { _tag: "Worktree", mainCheckout: null, git: null });
1025
+ identities.set(directory, { _tag: "Worktree", gitDir, mainCheckout: null, git: null });
1026
} else
1027
repositories.push({
1028
directory,
1029
gitDir: path.resolve(gitDir, commonDir),
1023
- linkedWorktree: true,
1030
+ worktreeGitDir: gitDir,
1031
});
1032
}
1033
1034
const configTexts = yield* readGitFiles(
1035
repositories.map(({ gitDir }) => path.join(gitDir, "config")),
1036
);
1030
- for (const { directory, gitDir, linkedWorktree } of repositories) {
1037
+ for (const { directory, gitDir, worktreeGitDir } of repositories) {
1038
const configText = configTexts.get(path.join(gitDir, "config")) ?? "";
1039
const originUrl = parseOriginUrlFromGitConfig(configText);
1040
const git: AgentSessionProjectGit = {
@@ -1036,9 +1043,10 @@ export const make = Effect.gen(function* () {
1043
repository: repositoryPathFromRemoteUrl(originUrl),
1044
};
1045
// Bare repositories have no main checkout, so offer their linked worktrees independently.
1039
- if (linkedWorktree && !isBareGitConfig(configText)) {
1046
+ if (worktreeGitDir !== null && !isBareGitConfig(configText)) {
1047
identities.set(directory, {
1048
_tag: "Worktree",
1049
+ gitDir: worktreeGitDir,
1050
// Only a common dir named .git sits inside its main checkout, and an
1051
// unreadable config can't rule out a bare repository.
1052
mainCheckout:
@@ -1052,6 +1060,61 @@ export const make = Effect.gen(function* () {
1060
return identities;
1061
});
1062
1063
+ /** Maps each directory to the project it counts toward: a linked worktree counts toward its main checkout. */
1064
+ const resolveDirectoryProjects = Effect.fn("AgentSessionScanner.resolveDirectoryProjects")(
1065
+ function* (resolvedDirectories: ReadonlyArray<string>) {
1066
+ // Stat every directory first so one batch reads all git identities.
1067
+ const directories = new Map<string, Option.Option<FileSystem.File.Info>>();
1068
+ for (const resolved of resolvedDirectories) {
1069
+ if (directories.has(resolved)) continue;
1070
+ directories.set(resolved, yield* projectDirectoryStats(resolved));
1071
+ }
1072
+ const directoryGitIdentities = yield* readGitIdentities(
1073
+ Array.from(directories).flatMap(([directory, stats]) =>
1074
+ Option.isSome(stats) ? [directory] : [],
1075
+ ),
1076
+ );
1077
+ const projects = new Map<
1078
+ string,
1079
+ {
1080
+ readonly key: string;
1081
+ readonly path: string;
1082
+ readonly git: AgentSessionProjectGit | null;
1083
+ readonly worktreeGitDir: string | null;
1084
+ } | null
1085
+ >();
1086
+ for (const [resolved, stats] of directories) {
1087
+ const gitIdentity = directoryGitIdentities.get(resolved);
1088
+ if (Option.isNone(stats) || gitIdentity === undefined) {
1089
+ projects.set(resolved, null);
1090
+ } else if (gitIdentity._tag === "Worktree") {
1091
+ const { mainCheckout } = gitIdentity;
1092
+ const mainStats =
1093
+ mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout);
1094
+ projects.set(
1095
+ resolved,
1096
+ mainCheckout !== null && Option.isSome(mainStats)
1097
+ ? {
1098
+ key: yield* directoryIdentity(mainCheckout, mainStats.value),
1099
+ path: mainCheckout,
1100
+ git: gitIdentity.git,
1101
+ worktreeGitDir: gitIdentity.gitDir,
1102
+ }
1103
+ : null,
1104
+ );
1105
+ } else {
1106
+ projects.set(resolved, {
1107
+ key: yield* directoryIdentity(resolved, stats.value),
1108
+ path: resolved,
1109
+ git: gitIdentity._tag === "Repository" ? gitIdentity.git : null,
1110
+ worktreeGitDir: null,
1111
+ });
1112
+ }
1113
+ }
1114
+ return projects;
1115
+ },
1116
+ );
1117
+
1118
const readCwd = Effect.fn("AgentSessionScanner.readCwd")(function* (
1119
source: AgentSessionSource,
1120
transcript: TranscriptCandidate,
@@ -1769,64 +1832,18 @@ export const make = Effect.gen(function* () {
1832
git: AgentSessionProjectGit | null;
1833
}
1834
>();
1772
- // Resolve every candidate directory first so one batch reads all git identities.
1773
- const directories = new Map<string, Option.Option<FileSystem.File.Info>>();
1774
- for (const candidate of raw) {
1775
- const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1776
- if (!path.isAbsolute(expanded)) continue;
1777
- const resolved = path.resolve(expanded);
1778
- if (directories.has(resolved)) continue;
1779
- directories.set(resolved, yield* projectDirectoryStats(resolved));
1780
- }
1781
- const directoryGitIdentities = yield* readGitIdentities(
1782
- Array.from(directories).flatMap(([directory, stats]) =>
1783
- Option.isSome(stats) ? [directory] : [],
1784
- ),
1835
+ const directoryProjects = yield* resolveDirectoryProjects(
1836
+ raw.flatMap((candidate) => {
1837
+ const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1838
+ return path.isAbsolute(expanded) ? [path.resolve(expanded)] : [];
1839
+ }),
1840
);
1841
1787
- const directoryProjects = new Map<
1788
- string,
1789
- {
1790
- readonly key: string;
1791
- readonly path: string;
1792
- readonly git: AgentSessionProjectGit | null;
1793
- } | null
1794
- >();
1795
-
1842
for (const candidate of raw) {
1843
const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1844
if (!path.isAbsolute(expanded)) continue;
1799
- const resolved = path.resolve(expanded);
1800
- const stats = directories.get(resolved);
1801
- if (stats === undefined || Option.isNone(stats)) continue;
1802
- let project = directoryProjects.get(resolved);
1803
- if (project === undefined) {
1804
- const gitIdentity = directoryGitIdentities.get(resolved);
1805
- if (gitIdentity === undefined) {
1806
- project = null;
1807
- } else if (gitIdentity._tag === "Worktree") {
1808
- // A linked worktree's sessions count toward its main checkout's project.
1809
- const { mainCheckout } = gitIdentity;
1810
- const mainStats =
1811
- mainCheckout === null ? Option.none() : yield* projectDirectoryStats(mainCheckout);
1812
- project =
1813
- mainCheckout !== null && Option.isSome(mainStats)
1814
- ? {
1815
- key: yield* directoryIdentity(mainCheckout, mainStats.value),
1816
- path: mainCheckout,
1817
- git: gitIdentity.git,
1818
- }
1819
- : null;
1820
- } else {
1821
- project = {
1822
- key: yield* directoryIdentity(resolved, stats.value),
1823
- path: resolved,
1824
- git: gitIdentity._tag === "Repository" ? gitIdentity.git : null,
1825
- };
1826
- }
1827
- directoryProjects.set(resolved, project);
1828
- }
1829
- if (project === null) continue;
1845
+ const project = directoryProjects.get(path.resolve(expanded));
1846
+ if (project === undefined || project === null) continue;
1847
1848
const existing = merged.get(project.key);
1849
if (!existing) {
@@ -1916,6 +1933,45 @@ export const make = Effect.gen(function* () {
1933
}
1934
const { candidates } = cachedCandidates;
1935
1936
+ // The scan counts a linked worktree's sessions toward its main checkout, so import them with it.
1937
+ const candidateDirectories = candidates.flatMap((candidate) => {
1938
+ const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1939
+ return path.isAbsolute(expanded) ? [path.resolve(expanded)] : [];
1940
+ });
1941
+ const directoryProjects = yield* resolveDirectoryProjects(candidateDirectories);
1942
+ const belongsToRoot = Effect.fn("AgentSessionScanner.belongsToRoot")(function* (
1943
+ resolved: string,
1944
+ ) {
1945
+ if ((yield* directoryIdentity(resolved)) === rootIdentity) return true;
1946
+ if (!directoryProjects.has(resolved)) {
1947
+ const project = (yield* resolveDirectoryProjects([resolved])).get(resolved) ?? null;
1948
+ directoryProjects.set(resolved, project);
1949
+ }
1950
+ return directoryProjects.get(resolved)?.key === rootIdentity;
1951
+ });
1952
+ const worktreesByDirectory = new Map<string, { path: string; branch: string | null } | null>();
1953
+ const rootWorktree = Effect.fn("AgentSessionScanner.rootWorktree")(function* (
1954
+ resolved: string,
1955
+ ) {
1956
+ const known = worktreesByDirectory.get(resolved);
1957
+ if (known !== undefined) return known;
1958
+ const gitDir =
1959
+ (yield* directoryIdentity(resolved)) === rootIdentity
1960
+ ? null
1961
+ : (directoryProjects.get(resolved)?.worktreeGitDir ?? null);
1962
+ let worktree: { path: string; branch: string | null } | null = null;
1963
+ if (gitDir !== null) {
1964
+ const headPath = path.join(gitDir, "HEAD");
1965
+ const head = (yield* readGitFiles([headPath])).get(headPath) ?? "";
1966
+ worktree = {
1967
+ path: resolved,
1968
+ branch: /^ref: refs\/heads\/(.+)$/.exec(head.trim())?.[1] ?? null,
1969
+ };
1970
+ }
1971
+ worktreesByDirectory.set(resolved, worktree);
1972
+ return worktree;
1973
+ });
1974
+
1975
const eligibleTranscripts: Array<{
1976
readonly candidate: RawCandidate;
1977
readonly transcript: RawCandidate["transcripts"][number] & { readonly mtimeMs: number };
@@ -1924,7 +1980,7 @@ export const make = Effect.gen(function* () {
1980
const expanded = expandHomePath(candidate.cwd.trim(), homeDir);
1981
if (!path.isAbsolute(expanded)) continue;
1982
const resolved = path.resolve(expanded);
1927
- if ((yield* directoryIdentity(resolved)) !== rootIdentity) continue;
1983
+ if (!(yield* belongsToRoot(resolved))) continue;
1984
1985
for (const transcript of candidate.transcripts) {
1986
if (
@@ -2055,12 +2111,10 @@ export const make = Effect.gen(function* () {
2111
projectCwd(snapshot.cwd.value, transcript.projectRoots).trim(),
2112
homeDir,
2113
);
2058
- if (
2059
- !path.isAbsolute(expandedCwd) ||
2060
- (yield* directoryIdentity(path.resolve(expandedCwd))) !== rootIdentity
2061
- ) {
2114
+ if (!path.isAbsolute(expandedCwd) || !(yield* belongsToRoot(path.resolve(expandedCwd)))) {
2115
return Option.some<AgentSessionRecentThread>({ _tag: "Skipped" });
2116
}
2117
+ const worktree = yield* rootWorktree(path.resolve(expandedCwd));
2118
2119
const inheritedRecords =
2120
candidate.source === "codex"
@@ -2116,6 +2170,7 @@ export const make = Effect.gen(function* () {
2170
thread:
2171
savedTitle === undefined ? parsedThread : { ...parsedThread, title: savedTitle },
2172
source,
2173
+ worktree,
2174
});
2175
}).pipe(importReadLock.withPermits(1)),
2176
),