Repository navigation
Expand file tree
/
Copy pathClaudeDriver.test.ts
More file actions
219 lines (214 loc) · 9.49 KB
/
Copy pathClaudeDriver.test.ts
File metadata and controls
219 lines (214 loc) · 9.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
// @effect-diagnostics-next-line nodeBuiltinImport:off -- the native SDK callback reads the child fixture's account outside Effect.
import * as NodeFSP from "node:fs/promises";
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { vi } from "vite-plus/test";
import * as ClaudeSdk from "@anthropic-ai/claude-agent-sdk";
import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
import { ProviderInstanceId } from "@t3tools/contracts";
import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
import * as ProviderHost from "@t3tools/provider-core/server/ProviderHost";
import * as ProviderLatestVersions from "@t3tools/provider-core/server/ProviderLatestVersions";
import * as ProviderEventLoggers from "@t3tools/provider-core/server/ProviderEventLoggers";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
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 Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import { HttpClient } from "effect/http";
import * as BackgroundPolicy from "../../background/BackgroundPolicy.ts";
import * as ServerConfig from "../../config.ts";
import * as ServerSettings from "../../serverSettings.ts";
import * as ModelManifest from "../ModelManifest.ts";
import * as ProviderInstallationGate from "../ProviderInstallationGate.ts";
import * as ResetCreditCoordinator from "../resetCreditCoordinator.ts";
import * as ClaudeAdapterV2 from "../../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
import { claudeCliFixtureSource } from "../ClaudeCliAuth.testkit.ts";
import { ClaudeDriver } from "./ClaudeDriver.ts";
vi.mock("@anthropic-ai/claude-agent-sdk", { spy: true });
const parseAccount = Schema.decodeSync(
Schema.fromJsonString(Schema.Struct({ email: Schema.String })),
);
const layerDeps = Layer.mergeAll(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-claude-driver-" }),
IdAllocator.layer,
McpProviderSessions.layer,
ServerSettings.layerTest(),
ModelManifest.layerTest,
ResetCreditCoordinator.layerTest,
ProviderInstallationGate.layer,
ProviderLatestVersions.layer,
Layer.mock(ClaudeAdapterV2.ClaudeAgentSdkQueryRunner)({}),
Layer.mock(BackgroundPolicy.BackgroundPolicy)({
shouldRunScopeWork: () => Effect.succeed(false),
}),
Layer.succeed(
ProviderEventLoggers.ProviderEventLoggers,
ProviderEventLoggers.NoOpProviderEventLoggers,
),
Layer.succeed(
HttpClient.HttpClient,
HttpClient.make(() => Effect.die("Fixture must not send HTTP")),
),
).pipe(Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)));
const layerTest = Layer.effect(
ProviderHost.ProviderHost,
Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const settings = yield* ServerSettings.ServerSettingsService;
return ProviderHost.ProviderHost.of({
compatibility: () => Effect.undefined,
paths: config,
settings: {
get: settings.getSettings,
withSnapshot: settings.withSettingsSnapshot,
changes: settings.streamChanges,
subscribe: settings.subscribeChanges,
},
shouldRunBackgroundWork: () => Effect.succeed(false),
resolveAttachmentPath: () => null,
credentials: () => Effect.die("Native Claude owns its credentials"),
});
}),
).pipe(Layer.provideMerge(layerDeps));
it.effect(
"invalidates the populated Claude account cache after native sign-in and guards text generation",
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { stateDir } = yield* ServerConfig.ServerConfig;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-driver-binary-" });
const binaryPath = path.join(root, "claude");
yield* fs.writeFileString(binaryPath, `#!${process.execPath}\n${claudeCliFixtureSource}`, {
mode: 0o755,
});
const instanceId = ProviderInstanceId.make("private");
const configDir = path.join(stateDir, "providers", "claude", instanceId, "cli");
yield* fs.makeDirectory(configDir, { recursive: true });
yield* fs.writeFileString(
path.join(configDir, "account.json"),
'{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"before@example.test"}',
);
const query = vi.spyOn(ClaudeSdk, "query").mockImplementation(
() =>
({
initializationResult: async () => {
const account = parseAccount(
await NodeFSP.readFile(path.join(configDir, "account.json"), "utf8"),
);
return {
commands: [],
agents: [],
models: [],
output_style: "default",
available_output_styles: [],
account: {
email: account.email,
subscriptionType: "pro",
tokenSource: "oauth",
apiProvider: "firstParty",
},
};
},
usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET: async () => ({
rate_limits_available: false,
rate_limits: null,
}),
}) as unknown as ReturnType<typeof ClaudeSdk.query>,
);
yield* Effect.addFinalizer(() => Effect.sync(() => query.mockRestore()));
const instance = yield* ClaudeDriver.create({
instanceId,
enabled: true,
displayName: "Private",
environment: [
{ name: "T3_TEST_EMAIL", value: "after@example.test", sensitive: false },
{ name: "CLAUDE_CONFIG_DIR", value: path.join(root, "shared"), sensitive: false },
],
config: {
...ClaudeDriver.defaultConfig(),
setupMode: "cli",
binaryPath,
shareProfile: false,
},
});
expect(instance.sharedSkillsDirectory).toBeUndefined();
expect((yield* instance.snapshot.refresh).auth.email).toBe("before@example.test");
expect((yield* instance.snapshot.refresh).auth.email).toBe("before@example.test");
const auth = instance.auth!;
yield* auth.start("owner");
const waiting = yield* auth.subscribe("owner").pipe(
Stream.filter((state) => state.phase === "waiting"),
Stream.runHead,
Effect.map(Option.getOrThrow),
);
expect(
(yield* instance.textGeneration
.generateThreadTitle({
cwd: root,
message: "Title",
modelSelection: { instanceId, model: "claude-sonnet-4-6" },
})
.pipe(Effect.flip)).detail,
).toBe("Provider sign-in is changing. Try again after it finishes.");
const refreshed = yield* instance.snapshot.streamChanges.pipe(
Stream.filter((snapshot) => snapshot.auth.email === "after@example.test"),
Stream.runHead,
Effect.map(Option.getOrThrow),
Effect.forkScoped,
);
yield* auth.complete!("owner", { flowId: waiting.flowId!, callbackUrl: "fixture-code" });
expect((yield* Fiber.join(refreshed)).auth).toMatchObject({
status: "authenticated",
email: "after@example.test",
});
expect(query.mock.calls).toHaveLength(2);
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
for (const conflict of [false, true]) {
it.effect.skipIf(!symlinksSupported)(
`materializes the profile at create with conflict=${conflict}`,
() =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { stateDir } = yield* ServerConfig.ServerConfig;
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-claude-driver-overlay-" });
const shared = path.join(root, "shared");
const instanceId = ProviderInstanceId.make("overlay");
const account = path.join(stateDir, "providers", "claude", instanceId, "cli");
yield* fs.makeDirectory(shared);
if (conflict) {
yield* fs.makeDirectory(account, { recursive: true });
yield* fs.writeFileString(path.join(account, "settings.json"), "account");
}
const create = ClaudeDriver.create({
instanceId,
enabled: false,
displayName: "Overlay",
environment: [{ name: "CLAUDE_CONFIG_DIR", value: shared, sensitive: false }],
config: { ...ClaudeDriver.defaultConfig(), setupMode: "cli" },
});
if (conflict) {
const error = yield* create.pipe(Effect.flip);
expect(error).toMatchObject({ _tag: "ProviderDriverError" });
expect(error.detail).toContain(path.join(account, "settings.json"));
expect(yield* fs.readFileString(path.join(account, "settings.json"))).toBe("account");
} else {
const instance = yield* create;
expect(yield* fs.readLink(path.join(account, "settings.json"))).toBe(
path.join(shared, "settings.json"),
);
expect(instance.sharedSkillsDirectory).toBe(path.join(shared, "skills"));
expect(instance.continuationIdentity.continuationKey).toBe(`claude:home:${account}`);
expect(instance.auth?.credentialBinding).toEqual({ owner: "provider", key: account });
}
}).pipe(Effect.scoped, Effect.provide(layerTest)),
);
}