GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Merge pull request 'fix(server): Claude threads recover when their se… · yasinuslu/t3code@b7ebb25

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • apps/server/src
    • orchestration-v2
      • Adapters
        • ClaudeAdapterV2.test.ts
        • ClaudeAdapterV2.ts
        • ClaudeResumeTranscript.test.ts
        • ClaudeResumeTranscript.ts
      • ProviderAdapter.ts
      • ProviderSessionManager.test.ts
      • ProviderSessionManager.ts
      • ProviderTurnStartService.test.ts
      • ProviderTurnStartService.ts
      • RuntimePolicy.ts
      • ThreadSettlementService.test.ts
      • ThreadSettlementService.ts
    • provider/Drivers
      • ClaudeDriver.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+59Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ import * as Stream from "effect/Stream";
4646
import { Tool } from "effect/unstable/ai";
4747
import { formatClaudeResumeCompactionQuestion } from "@t3tools/shared/claudeCompaction";
4848
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
49+
import { PROMPT_NOT_RUN_FAILURE_CODE } from "@t3tools/shared/orchestrationV2ThreadError";
4950
import { SpawnExecutableResolution } from "@t3tools/shared/shell";
5051

5152
import { attachmentRelativePath } from "../../attachmentStore.ts";
@@ -4082,6 +4083,64 @@ describe("ClaudeAdapterV2 background wake turns", () => {
40824083
),
40834084
);
40844085

4086+
it.effect("turns a lost Claude session into an unrun prompt that will not be resumed again", () =>
4087+
Effect.scoped(
4088+
Effect.gen(function* () {
4089+
const harness = yield* makeWakeHarness;
4090+
const now = yield* DateTime.now;
4091+
yield* harness.runtime.startTurn(
4092+
makeClaudeTestTurnInput({
4093+
threadId: harness.threadId,
4094+
providerThread: harness.providerThread,
4095+
now,
4096+
attemptId: RunAttemptId.make("attempt-claude-lost-session"),
4097+
text: "Continue.",
4098+
attachments: [],
4099+
}),
4100+
);
4101+
yield* Queue.offer(
4102+
harness.sdkMessages,
4103+
claudeSdkFrame({
4104+
type: "result",
4105+
subtype: "error_during_execution",
4106+
duration_ms: 0,
4107+
duration_api_ms: 0,
4108+
is_error: true,
4109+
num_turns: 0,
4110+
stop_reason: null,
4111+
total_cost_usd: 0,
4112+
usage: {
4113+
input_tokens: 0,
4114+
output_tokens: 0,
4115+
cache_creation_input_tokens: 0,
4116+
cache_read_input_tokens: 0,
4117+
},
4118+
modelUsage: {},
4119+
permission_denials: [],
4120+
errors: [`No conversation found with session ID: ${WAKE_NATIVE_SESSION}`],
4121+
uuid: "00000000-0000-4000-8000-000000000301",
4122+
session_id: WAKE_NATIVE_SESSION,
4123+
}),
4124+
);
4125+
yield* awaitUntil(() => harness.terminalEvents().length === 1, "lost-session terminal");
4126+
const terminal = harness.terminalEvents()[0];
4127+
assert.equal(terminal?.status, "failed");
4128+
assert.equal(terminal?.failure?.code, PROMPT_NOT_RUN_FAILURE_CODE);
4129+
4130+
// The resend must start a fresh session instead of resuming this one.
4131+
const resumed = yield* Effect.exit(
4132+
harness.runtime.resumeThread({
4133+
providerThread: { ...harness.providerThread, lastRunOrdinal: 1 },
4134+
threadId: harness.threadId,
4135+
modelSelection: CLAUDE_TEST_MODEL_SELECTION,
4136+
runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,
4137+
}),
4138+
);
4139+
assert.isTrue(Exit.isFailure(resumed));
4140+
}).pipe(Effect.provide(Layer.merge(IdAllocator.layer, NodeServices.layer))),
4141+
),
4142+
);
4143+
40854144
it.effect(
40864145
"clears the replaced sibling native thread roster when openQuery switches processes",
40874146
() =>
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Copy file name to clipboardExpand all lines: apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+103-6Lines changed: 103 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,7 @@ import * as IdAllocator from "../IdAllocator.ts";
133133
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
134134
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
135135
import { providerMessageTextWithAttachmentPaths } from "../AttachmentPrompt.ts";
136+
import { ensureClaudeResumeTranscript } from "./ClaudeResumeTranscript.ts";
136137
import * as ProviderAdapter from "../ProviderAdapter.ts";
137138
import {
138139
ProviderAdapterDriverCreateError,
@@ -2382,6 +2383,17 @@ function terminalResultError(
23822383
}
23832384
}
23842385

2386+
/** The CLI could not load the session it was asked to resume, so it ran nothing. */
2387+
export function isClaudeSessionNotFoundResult(result: SDKResultMessage): boolean {
2388+
return (
2389+
result.subtype !== "success" &&
2390+
result.num_turns === 0 &&
2391+
result.errors.some(
2392+
(error) => typeof error === "string" && error.startsWith("No conversation found"),
2393+
)
2394+
);
2395+
}
2396+
23852397
function isOverloadedResult(result: SDKResultMessage): boolean {
23862398
return result.subtype === "success" && result.api_error_status === 529;
23872399
}
@@ -3013,6 +3025,8 @@ export interface ClaudeAdapterV2Options {
30133025
readonly onUsageLimits?: ServerProviderShape["applyUsageLimits"];
30143026
/** Resolves CLAUDE_CONFIG_DIR per project from code profiles or `homePathCommand`. */
30153027
readonly configDirResolver?: ClaudeConfigDirResolver;
3028+
/** Other Claude config dirs a session's transcript may have been written to. */
3029+
readonly transcriptSearchConfigDirs?: Effect.Effect<ReadonlyArray<string>>;
30163030
/**
30173031
* Receives the full command list whenever a session reloads it
30183032
* (`/reload-skills`, `/reload-plugins`, skills found mid-session), so the
@@ -3104,16 +3118,21 @@ export function makeClaudeAdapterV2(
31043118
// process, skill scan and sign-in hint of the session uses one dir.
31053119
const projectConfigDir =
31063120
adapterOptions.configDirResolver !== undefined && input.runtimePolicy.cwd !== null
3107-
? yield* adapterOptions.configDirResolver.resolveForWorkspace(input.runtimePolicy.cwd)
3121+
? yield* adapterOptions.configDirResolver.resolveForWorkspace(
3122+
input.runtimePolicy.cwd,
3123+
input.runtimePolicy.projectRoot,
3124+
)
31083125
: undefined;
31093126
const sessionEnvironment: NodeJS.ProcessEnv =
31103127
projectConfigDir === undefined
31113128
? adapterOptions.environment
31123129
: { ...adapterOptions.environment, CLAUDE_CONFIG_DIR: projectConfigDir.path };
3130+
const sessionConfigDir = yield* resolveClaudeHomePath(
3131+
{ homePath: "" },
3132+
sessionEnvironment,
3133+
).pipe(Effect.provideService(Path.Path, path));
31133134
const configuredConfigDir = describeClaudeConfigDir(
3114-
yield* resolveClaudeHomePath({ homePath: "" }, sessionEnvironment).pipe(
3115-
Effect.provideService(Path.Path, path),
3116-
),
3135+
sessionConfigDir,
31173136
projectConfigDir?.profile,
31183137
);
31193138
// Holds the latest session record: the CLI reports the dir it actually
@@ -3141,6 +3160,10 @@ export function makeClaudeAdapterV2(
31413160
// created, never resumed, even on a provider thread with earlier
31423161
// turns (a fresh native session after a failed resume).
31433162
const unpromptedNativeThreads = yield* Ref.make(new Set<string>());
3163+
// Sessions the CLI said it could not find ("No conversation found").
3164+
// Resuming them again fails the same way, so resumeThread refuses
3165+
// them and T3 starts a fresh session instead.
3166+
const lostNativeThreads = yield* Ref.make(new Set<string>());
31443167
const latestPlanByKind = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact>());
31453168
const planIdsByNativeItem = yield* Ref.make(
31463169
new Map<string, OrchestrationV2PlanArtifact["id"]>(),
@@ -6533,9 +6556,22 @@ export function makeClaudeAdapterV2(
65336556
resetTimes.length > 0 && resetTimes.every((time) => time !== null)
65346557
? resetTimes.reduce((latest, time) => (time! > latest ? time! : latest), "")
65356558
: null;
6559+
const sessionLost = !interrupted && isClaudeSessionNotFoundResult(message);
6560+
if (sessionLost) {
6561+
yield* Ref.update(lostNativeThreads, (current) =>
6562+
new Set(current).add(message.session_id),
6563+
);
6564+
}
65366565
const resultFailure = interrupted
65376566
? null
6538-
: providerFailureFromResult(message, failureHint, usageLimited);
6567+
: sessionLost
6568+
? // The prompt never ran; the resend starts a fresh session.
6569+
makeProviderFailure({
6570+
message: resultUserFacingError(message),
6571+
code: PROMPT_NOT_RUN_FAILURE_CODE,
6572+
class: "provider_error",
6573+
})
6574+
: providerFailureFromResult(message, failureHint, usageLimited);
65396575
const terminalFailure =
65406576
resultFailure?.class === "usage_limit"
65416577
? { ...resultFailure, resetAt }
@@ -7348,6 +7384,58 @@ export function makeClaudeAdapterV2(
73487384
return context;
73497385
});
73507386

7387+
// Fails when the CLI could not resume this provider thread's session,
7388+
// so T3 starts a fresh one seeded with the thread's history instead of
7389+
// failing the turn with "No conversation found". A transcript written
7390+
// under another cwd or config dir is copied to where the CLI looks.
7391+
const assertResumableNativeThread = Effect.fnUntraced(function* (
7392+
providerThread: OrchestrationV2ProviderThread,
7393+
) {
7394+
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
7395+
const cwd = input.runtimePolicy.cwd;
7396+
if (nativeThreadId == null) return;
7397+
const lost = (yield* Ref.get(lostNativeThreads)).has(nativeThreadId);
7398+
if (
7399+
!lost &&
7400+
(cwd === null ||
7401+
providerThread.lastRunOrdinal === null ||
7402+
(yield* Ref.get(unpromptedNativeThreads)).has(nativeThreadId) ||
7403+
(yield* Ref.get(queryContext))?.nativeThreadId === nativeThreadId)
7404+
) {
7405+
return;
7406+
}
7407+
const transcript =
7408+
lost || cwd === null
7409+
? ({ _tag: "missing" } as const)
7410+
: yield* ensureClaudeResumeTranscript({
7411+
configDir: sessionConfigDir,
7412+
cwd,
7413+
sessionId: nativeThreadId,
7414+
...(adapterOptions.transcriptSearchConfigDirs
7415+
? { searchConfigDirs: adapterOptions.transcriptSearchConfigDirs }
7416+
: {}),
7417+
}).pipe(
7418+
Effect.provideService(FileSystem.FileSystem, fileSystem),
7419+
Effect.provideService(Path.Path, path),
7420+
);
7421+
if (transcript._tag === "copied") {
7422+
yield* Effect.logInfo("Copied a Claude transcript so its session can resume", {
7423+
nativeThreadId,
7424+
from: transcript.from,
7425+
configDir: sessionConfigDir,
7426+
cwd,
7427+
});
7428+
}
7429+
if (transcript._tag === "missing") {
7430+
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
7431+
driver: CLAUDE_PROVIDER,
7432+
detail: lost
7433+
? `Claude could not find session ${nativeThreadId}.`
7434+
: `Claude session ${nativeThreadId} has no transcript under ${sessionConfigDir}.`,
7435+
});
7436+
}
7437+
});
7438+
73517439
const startTurn = Effect.fn("ClaudeAdapterV2.startTurn")(
73527440
function* (turnInput: ProviderAdapter.ProviderAdapterV2TurnInput) {
73537441
const startedAt = yield* DateTime.now;
@@ -7756,6 +7844,10 @@ export function makeClaudeAdapterV2(
77567844
}
77577845
return false;
77587846
}),
7847+
needsResume: (providerThread) =>
7848+
Ref.get(lostNativeThreads).pipe(
7849+
Effect.map((lost) => lost.has(providerThread.nativeThreadRef?.nativeId ?? "")),
7850+
),
77597851
hasPendingBackgroundWorkForThread: (providerThread) =>
77607852
Effect.gen(function* () {
77617853
const nativeThreadId = providerThread.nativeThreadRef?.nativeId;
@@ -7801,6 +7893,7 @@ export function makeClaudeAdapterV2(
78017893
),
78027894
resumeThread: Effect.fn("ClaudeAdapterV2.resumeThread")(
78037895
function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
7896+
yield* assertResumableNativeThread(threadInput.providerThread);
78047897
const updatedAt = yield* DateTime.now;
78057898
return {
78067899
...threadInput.providerThread,
@@ -8048,7 +8141,11 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
80488141
input: ProviderAdapterDriverCreateInput<ClaudeSettings>,
80498142
hooks: Pick<
80508143
ClaudeAdapterV2Options,
8051-
"scopedLimitNames" | "onUsageLimits" | "configDirResolver" | "onCommandsChanged"
8144+
| "scopedLimitNames"
8145+
| "onUsageLimits"
8146+
| "configDirResolver"
8147+
| "transcriptSearchConfigDirs"
8148+
| "onCommandsChanged"
80528149
> = {},
80538150
) {
80548151
const { instanceId, environment, enabled, config } = input;
Collapse file

‎apps/server/src/orchestration-v2/Adapters/ClaudeResumeTranscript.test.ts‎

Copy file name to clipboard
+139Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { describe, expect, it } from "@effect/vitest";
3+
import * as Effect from "effect/Effect";
4+
import * as FileSystem from "effect/FileSystem";
5+
import * as Path from "effect/Path";
6+
7+
import { claudeProjectDirName, ensureClaudeResumeTranscript } from "./ClaudeResumeTranscript.ts";
8+
9+
const SESSION = "0c907d22-4291-42fa-8316-2d2a1ccdf5be";
10+
11+
const writeTranscript = Effect.fn(function* (configDir: string, cwd: string) {
12+
const fs = yield* FileSystem.FileSystem;
13+
const path = yield* Path.Path;
14+
const dir = path.join(configDir, "projects", claudeProjectDirName(cwd));
15+
yield* fs.makeDirectory(path.join(dir, SESSION, "tool-results"), { recursive: true });
16+
yield* fs.writeFileString(path.join(dir, `${SESSION}.jsonl`), '{"type":"user"}\n');
17+
yield* fs.writeFileString(path.join(dir, SESSION, "tool-results", "a.txt"), "out");
18+
});
19+
20+
describe("ensureClaudeResumeTranscript", () => {
21+
it("maps a cwd to Claude's project dir name", () => {
22+
expect(claudeProjectDirName("/home/u/.t3/worktrees/t3code/feat-x")).toBe(
23+
"-home-u--t3-worktrees-t3code-feat-x",
24+
);
25+
});
26+
27+
it.effect("finds the transcript where the CLI looks", () =>
28+
Effect.gen(function* () {
29+
const fs = yield* FileSystem.FileSystem;
30+
const home = yield* fs.makeTempDirectoryScoped();
31+
yield* writeTranscript(home, "/work/repo");
32+
const status = yield* ensureClaudeResumeTranscript({
33+
configDir: home,
34+
cwd: "/work/repo",
35+
sessionId: SESSION,
36+
});
37+
expect(status._tag).toBe("present");
38+
}).pipe(Effect.provide(NodeServices.layer)),
39+
);
40+
41+
it.effect("copies the transcript after the thread moved to another cwd", () =>
42+
Effect.gen(function* () {
43+
const fs = yield* FileSystem.FileSystem;
44+
const path = yield* Path.Path;
45+
const home = yield* fs.makeTempDirectoryScoped();
46+
yield* writeTranscript(home, "/work/worktrees/feat-x");
47+
const status = yield* ensureClaudeResumeTranscript({
48+
configDir: home,
49+
cwd: "/work/repo",
50+
sessionId: SESSION,
51+
});
52+
expect(status._tag).toBe("copied");
53+
const target = path.join(home, "projects", claudeProjectDirName("/work/repo"));
54+
expect(yield* fs.readFileString(path.join(target, `${SESSION}.jsonl`))).toBe(
55+
'{"type":"user"}\n',
56+
);
57+
expect(yield* fs.exists(path.join(target, SESSION, "tool-results", "a.txt"))).toBe(true);
58+
}).pipe(Effect.provide(NodeServices.layer)),
59+
);
60+
61+
it.effect("copies the transcript from the config dir that wrote it", () =>
62+
Effect.gen(function* () {
63+
const fs = yield* FileSystem.FileSystem;
64+
const path = yield* Path.Path;
65+
const writer = yield* fs.makeTempDirectoryScoped();
66+
const other = yield* fs.makeTempDirectoryScoped();
67+
yield* writeTranscript(writer, "/work/repo");
68+
const status = yield* ensureClaudeResumeTranscript({
69+
configDir: other,
70+
cwd: "/work/repo",
71+
sessionId: SESSION,
72+
searchConfigDirs: Effect.succeed([writer]),
73+
});
74+
expect(status).toEqual({
75+
_tag: "copied",
76+
from: path.join(writer, "projects", claudeProjectDirName("/work/repo"), `${SESSION}.jsonl`),
77+
});
78+
}).pipe(Effect.provide(NodeServices.layer)),
79+
);
80+
81+
it.effect("reports a transcript that is gone everywhere", () =>
82+
Effect.gen(function* () {
83+
const fs = yield* FileSystem.FileSystem;
84+
const home = yield* fs.makeTempDirectoryScoped();
85+
const status = yield* ensureClaudeResumeTranscript({
86+
configDir: home,
87+
cwd: "/work/repo",
88+
sessionId: SESSION,
89+
searchConfigDirs: Effect.succeed(["/nonexistent/claude"]),
90+
});
91+
expect(status._tag).toBe("missing");
92+
}).pipe(Effect.provide(NodeServices.layer)),
93+
);
94+
it.effect("copies the most recently written transcript when several exist", () =>
95+
Effect.gen(function* () {
96+
const fs = yield* FileSystem.FileSystem;
97+
const path = yield* Path.Path;
98+
const home = yield* fs.makeTempDirectoryScoped();
99+
yield* writeTranscript(home, "/work/old");
100+
yield* writeTranscript(home, "/work/new");
101+
const newer = path.join(
102+
home,
103+
"projects",
104+
claudeProjectDirName("/work/new"),
105+
`${SESSION}.jsonl`,
106+
);
107+
yield* fs.writeFileString(newer, '{"type":"user"}\n{"type":"assistant"}\n');
108+
yield* fs.utimes(
109+
path.join(home, "projects", claudeProjectDirName("/work/old"), `${SESSION}.jsonl`),
110+
1,
111+
1,
112+
);
113+
const status = yield* ensureClaudeResumeTranscript({
114+
configDir: home,
115+
cwd: "/work/repo",
116+
sessionId: SESSION,
117+
});
118+
expect(status).toEqual({ _tag: "copied", from: newer });
119+
}).pipe(Effect.provide(NodeServices.layer)),
120+
);
121+
122+
it.effect("looks under the real path of a symlinked cwd, like the CLI", () =>
123+
Effect.gen(function* () {
124+
const fs = yield* FileSystem.FileSystem;
125+
const path = yield* Path.Path;
126+
const home = yield* fs.makeTempDirectoryScoped();
127+
const real = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
128+
const link = path.join(home, "link");
129+
yield* fs.symlink(real, link);
130+
yield* writeTranscript(home, real);
131+
const status = yield* ensureClaudeResumeTranscript({
132+
configDir: home,
133+
cwd: link,
134+
sessionId: SESSION,
135+
});
136+
expect(status._tag).toBe("present");
137+
}).pipe(Effect.provide(NodeServices.layer)),
138+
);
139+
});

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.