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, 16:00 UTC
fix(server): repeated imports reach older worktree history (#36608)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 14, 2026 at 10:55 UTC
13f89ae0a7fcecbdcd06ac1551d5ff549bb76926
2 files changed
+164
-16
apps/server/src/project/AgentSessionImporter.test.ts
+144
-4
@@ -1,3 +1,4 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
import { expect, it } from "@effect/vitest";
3
import {
4
type AgentSessionSource,
@@ -22,17 +23,21 @@ import * as Context from "effect/Context";
23
import * as DateTime from "effect/DateTime";
24
import * as Deferred from "effect/Deferred";
25
import * as Effect from "effect/Effect";
26
+import * as FileSystem from "effect/FileSystem";
27
import * as Fiber from "effect/Fiber";
28
import * as Layer from "effect/Layer";
29
import * as Option from "effect/Option";
30
+import * as Path from "effect/Path";
31
import * as Stream from "effect/Stream";
32
import * as SqlClient from "effect/sql/SqlClient";
33
import * as TestClock from "effect/testing/TestClock";
34
35
+import * as ServerConfig from "../config.ts";
36
import * as EventSink from "../orchestration-v2/EventSink.ts";
37
import * as EventStore from "../orchestration-v2/EventStore.ts";
38
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
39
import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
40
+import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
41
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
42
import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
43
import {
@@ -188,6 +193,10 @@ const makeImporter = Effect.fn(function* (
193
ServerSettings.ServerSettingsService,
194
ServerSettingsError
195
> = ServerSettings.layerTest(),
196
+ realScan?: {
197
+ readonly workspaceRoot: string;
198
+ readonly scanner: AgentSessionScanner.AgentSessionScanner["Service"];
199
+ },
200
) {
201
const sql = yield* SqlClient.SqlClient;
202
const events = yield* EventStore.EventStoreV2;
@@ -229,15 +238,17 @@ const makeImporter = Effect.fn(function* (
238
ProviderSessionRuntime.ProviderSessionRuntimeRepository,
239
yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository,
240
),
232
- Layer.mock(AgentSessionScanner.AgentSessionScanner)({
233
- recentThreads: () => Stream.fromIterable(candidates),
234
- }),
241
+ realScan === undefined
242
+ ? Layer.mock(AgentSessionScanner.AgentSessionScanner)({
243
+ recentThreads: () => Stream.fromIterable(candidates),
244
+ })
245
+ : Layer.succeed(AgentSessionScanner.AgentSessionScanner, realScan.scanner),
246
Layer.mock(ProjectService.ProjectService)({
247
getById: () =>
248
Effect.succeedSome({
249
id: projectId,
250
title: "Project",
240
- workspaceRoot: "/workspace/project",
251
+ workspaceRoot: realScan?.workspaceRoot ?? "/workspace/project",
252
defaultModelSelection: null,
253
scripts: [],
254
createdAt: timestamp,
@@ -377,6 +388,43 @@ it.effect(
388
}).pipe(Effect.scoped, Effect.provide(persistence)),
389
);
390
391
+it.effect("tolerates a missing transcript owner but propagates failed ownership reads", () =>
392
+ Effect.gen(function* () {
393
+ const sql = yield* SqlClient.SqlClient;
394
+ const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository;
395
+ const source = candidate(CODEX_MODEL_SELECTION, "ownership-read");
396
+ const threadId = importId(source);
397
+ yield* runtimes.upsert({
398
+ threadId: ThreadId.make("missing-owner"),
399
+ providerName: "codex",
400
+ providerInstanceId: source.source.providerInstanceId,
401
+ adapterKey: "codex",
402
+ runtimeMode: "full-access",
403
+ status: "stopped",
404
+ lastSeenAt: timestamp,
405
+ resumeCursor: null,
406
+ runtimePayload: { importedTranscripts: [source.source] },
407
+ });
408
+ yield* runtimes.recordImportedTranscript({
409
+ threadId: ThreadId.make("missing-owner"),
410
+ source: source.source,
411
+ });
412
+ const importer = yield* makeImporter([source]);
413
+ expect(yield* importer.run).toEqual({ importedCount: 1, skippedCount: 0 });
414
+
415
+ yield* sql`UPDATE orchestration_v2_projection_threads SET payload_json = '{}' WHERE thread_id = ${threadId}`;
416
+ expect(yield* Effect.flip(importer.run)).toMatchObject({
417
+ _tag: "AgentSessionScanError",
418
+ operation: "read-projects",
419
+ cause: {
420
+ _tag: "OrchestratorProjectionError",
421
+ threadId,
422
+ cause: { _tag: "ProjectionStoreReadError" },
423
+ },
424
+ });
425
+ }).pipe(Effect.scoped, Effect.provide(persistence)),
426
+);
427
+
428
it.effect("rechecks ownership after the import reaches the commit transaction", () =>
429
Effect.gen(function* () {
430
const enteringTransaction = yield* Deferred.make<void>();
@@ -869,3 +917,95 @@ it.effect("imports under a policy ceiling in the project's default, kept under t
917
);
918
}).pipe(Effect.scoped, Effect.provide(persistence)),
919
);
920
+
921
+it.effect("repeated imports reach linked-worktree sessions behind the scan budget", () =>
922
+ Effect.gen(function* () {
923
+ const fs = yield* FileSystem.FileSystem;
924
+ const path = yield* Path.Path;
925
+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-import-worktree-budget-" });
926
+ const repo = path.join(root, "repo");
927
+ const worktree = path.join(root, "feature");
928
+ const worktreeGitDir = path.join(repo, ".git", "worktrees", "feature");
929
+ yield* fs.makeDirectory(worktreeGitDir, { recursive: true });
930
+ yield* fs.makeDirectory(worktree);
931
+ yield* fs.writeFileString(path.join(repo, ".git", "config"), "[core]\n");
932
+ yield* fs.writeFileString(path.join(worktreeGitDir, "commondir"), "../..\n");
933
+ yield* fs.writeFileString(path.join(worktreeGitDir, "HEAD"), "ref: refs/heads/feature\n");
934
+ yield* fs.writeFileString(path.join(worktree, ".git"), `gitdir: ${worktreeGitDir}\n`);
935
+
936
+ const claudeHome = path.join(root, "claude");
937
+ const codexHome = path.join(root, "codex");
938
+ const sessions = path.join(codexHome, "sessions", "2026", "09", "01");
939
+ yield* fs.makeDirectory(sessions, { recursive: true });
940
+ const nowMs = DateTime.toEpochMillis(now);
941
+ yield* TestClock.setTime(nowMs);
942
+ // One more session than the 100-transcript scan budget, all run in the linked worktree.
943
+ for (let index = 0; index < 101; index++) {
944
+ const file = path.join(sessions, `rollout-${String(index).padStart(3, "0")}.jsonl`);
945
+ const records = [
946
+ { type: "session_meta", payload: { id: `session-${index}`, cwd: worktree } },
947
+ { type: "event_msg", payload: { type: "user_message", message: `Request ${index}` } },
948
+ {
949
+ type: "response_item",
950
+ payload: {
951
+ type: "message",
952
+ role: "assistant",
953
+ content: [{ type: "output_text", text: "Done" }],
954
+ },
955
+ },
956
+ ];
957
+ yield* fs.writeFileString(
958
+ file,
959
+ records.map((record) => JSON.stringify(record) + "\n").join(""),
960
+ );
961
+ const modifiedAtSeconds = nowMs / 1000 - (index + 1);
962
+ yield* fs.utimes(file, modifiedAtSeconds, modifiedAtSeconds);
963
+ }
964
+
965
+ const scannerContext = yield* Layer.build(
966
+ AgentSessionScanner.layer.pipe(
967
+ Layer.provide(
968
+ Layer.mergeAll(
969
+ ServerConfig.layerTest(claudeHome, { prefix: "t3-import-budget-config-" }),
970
+ ServerSettings.layerTest({
971
+ providerInstances: {
972
+ [ProviderInstanceId.make("claudeAgent")]: {
973
+ driver: ProviderDriverKind.make("claudeAgent"),
974
+ config: { homePath: claudeHome },
975
+ },
976
+ [ProviderInstanceId.make("codex")]: {
977
+ driver: ProviderDriverKind.make("codex"),
978
+ config: { homePath: codexHome },
979
+ },
980
+ // Keeps the default Pi instance off the developer's real ~/.pi.
981
+ [ProviderInstanceId.make("pi")]: {
982
+ driver: ProviderDriverKind.make("pi"),
983
+ enabled: false,
984
+ config: {},
985
+ },
986
+ },
987
+ }),
988
+ Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Effect.succeed([]) }),
989
+ Layer.succeed(
990
+ ProviderSessionRuntime.ProviderSessionRuntimeRepository,
991
+ yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository,
992
+ ),
993
+ ),
994
+ ),
995
+ ),
996
+ );
997
+ const importer = yield* makeImporter([], Effect.void, undefined, undefined, undefined, {
998
+ workspaceRoot: repo,
999
+ scanner: Context.get(scannerContext, AgentSessionScanner.AgentSessionScanner),
1000
+ });
1001
+
1002
+ expect(yield* importer.run).toEqual({ importedCount: 100, skippedCount: 1 });
1003
+ expect(yield* importer.run).toEqual({ importedCount: 101, skippedCount: 0 });
1004
+ const oldest = yield* ProjectionStore.ProjectionStoreV2.pipe(
1005
+ Effect.flatMap((projections) =>
1006
+ projections.getThread(ThreadId.make("import:codex:session-100")),
1007
+ ),
1008
+ );
1009
+ expect(oldest.worktreePath).toBe(worktree);
1010
+ }).pipe(Effect.scoped, Effect.provide(Layer.merge(persistence, NodeServices.layer))),
1011
+);
apps/server/src/project/AgentSessionImporter.ts
+20
-12
@@ -35,6 +35,7 @@ import * as Stream from "effect/Stream";
35
import * as EventSink from "../orchestration-v2/EventSink.ts";
36
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
37
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
38
+import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts";
39
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
40
import * as ThreadCommandExecutor from "../orchestration-v2/ThreadCommandExecutor.ts";
41
import * as ProviderSessionRuntime from "../persistence/ProviderSessionRuntime.ts";
@@ -42,6 +43,10 @@ import * as ServerSettings from "../serverSettings.ts";
43
import * as AgentSessionScanner from "./AgentSessionScanner.ts";
44
import * as ProjectService from "./ProjectService.ts";
45
46
+const isProjectionStoreThreadNotFoundError = Schema.is(
47
+ ProjectionStore.ProjectionStoreThreadNotFoundError,
48
+);
49
+
50
const IMPORT_EVENT_PREFIX = "agent-session-import:v2";
51
const CLAUDE_SESSION_ID_PATTERN =
52
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -242,18 +247,21 @@ const make = Effect.gen(function* () {
247
(cause) => new AgentSessionScanError({ operation: "read-projects", cause }),
248
),
249
);
245
- const completedSources = runtimeRows.flatMap((runtime) => {
246
- const payload = AgentSessionScanner.decodeImportedTranscriptPayload(runtime.runtimePayload);
247
- if (
248
- Option.isNone(payload) ||
249
- payload.value.cwd === undefined ||
250
- normalizeProjectPathForComparison(payload.value.cwd) !==
251
- normalizeProjectPathForComparison(project.workspaceRoot)
252
- ) {
253
- return [];
254
- }
255
- return payload.value.importedTranscripts ?? [];
256
- });
250
+ // The thread's project owns its transcripts: a linked worktree import records the worktree as cwd.
251
+ const completedSources = (yield* Effect.forEach(runtimeRows, (runtime) => {
252
+ const imported = AgentSessionScanner.decodeImportedTranscriptPayload(
253
+ runtime.runtimePayload,
254
+ ).pipe(Option.flatMapNullishOr((payload) => payload.importedTranscripts));
255
+ if (Option.isNone(imported) || imported.value.length === 0) return Effect.succeed([]);
256
+ return orchestrator.getThreadRecords(runtime.threadId, []).pipe(
257
+ Effect.map(({ thread }) => (thread.projectId === input.projectId ? imported.value : [])),
258
+ Effect.catch((cause) =>
259
+ isProjectionStoreThreadNotFoundError(cause.cause)
260
+ ? Effect.succeed([])
261
+ : Effect.fail(new AgentSessionScanError({ operation: "read-projects", cause })),
262
+ ),
263
+ );
264
+ })).flat();
265
const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources);
266
const importedThreadIds = new Set<ThreadId>();
267
let importedCount = 0;