Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
105 changes: 105 additions & 0 deletions apps/server/src/provider/Layers/ClaudeAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Random from "effect/Random";
Expand Down Expand Up @@ -996,6 +997,110 @@ describe("ClaudeAdapterLive", () => {
);
});

it.effect("does not strand a running turn when an attachment cannot be read", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const eventsFiber = yield* Stream.take(adapter.streamEvents, 4).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});

const rejected = yield* adapter
.sendTurn({
threadId: session.threadId,
input: "Read the missing image",
attachments: [
{
type: "image",
id: "thread-claude-attachment-12345678-1234-1234-1234-123456789abc",
name: "missing.png",
mimeType: "image/png",
sizeBytes: 4,
},
],
})
.pipe(Effect.exit);
assert.equal(Exit.isFailure(rejected), true);

const accepted = yield* adapter.sendTurn({
threadId: session.threadId,
input: "Continue without the image",
attachments: [],
});
const events = Array.from(yield* Fiber.join(eventsFiber));
assert.deepEqual(
events.map((event) => event.type),
["session.started", "session.configured", "session.state.changed", "turn.started"],
);
assert.equal(events[3]?.type, "turn.started");
if (events[3]?.type === "turn.started") {
assert.equal(String(events[3].turnId), String(accepted.turnId));
}
const prompt = yield* Effect.promise(() =>
readFirstPromptMessage(harness.getLastCreateQueryInput()),
);
assert.deepEqual(prompt?.message.content, [
{ type: "text", text: "Continue without the image" },
]);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});

it.effect("rejects a send whose Claude session stops during provider setup", () => {
const harness = makeHarness();
let enteredResolve: (() => void) | undefined;
let releaseResolve: (() => void) | undefined;
const entered = new Promise<void>((resolve) => {
enteredResolve = resolve;
});
const release = new Promise<void>((resolve) => {
releaseResolve = resolve;
});
Object.assign(harness.query, {
setModel: async () => {
enteredResolve?.();
await release;
},
});
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const sending = yield* adapter
.sendTurn({
threadId: session.threadId,
input: "Do the work",
attachments: [],
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
SYNTHETIC_CLAUDE_CAPABLE_MODEL,
),
})
.pipe(Effect.result, Effect.forkChild);
yield* Effect.promise(() => entered);
yield* adapter.stopSession(session.threadId);
releaseResolve?.();
const result = yield* Fiber.join(sending);
assert.equal(result._tag, "Failure");
assert.equal(yield* adapter.hasSession(session.threadId), false);
assert.equal(harness.query.closeCalls, 1);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});

// The Claude CLI reads a streamed user message as a slash-command invocation
// only when the final content block is text. Leading with the text block sent
// every image-carrying turn down the plain-prompt path, so `/skill args`
Expand Down
62 changes: 35 additions & 27 deletions apps/server/src/provider/Layers/ClaudeAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5582,8 +5582,12 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const sendTurnUnlocked: ClaudeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
const context = yield* requireSession(input.threadId);
if (context.quarantined) return yield* exactUnavailable();
invalidateExactHistory(context);
yield* updateResumeCursor(context);
const lifecycleToken = sessionLifecycleTokens.get(input.threadId);
const requireCurrentContext = Effect.suspend(() =>
sessions.get(input.threadId) === context && !context.stopped && lifecycleToken
? requireLifecycleToken(input.threadId, lifecycleToken)
: Effect.fail(staleSessionOperation()),
);
const modelCatalog = yield* modelCatalogEffect;
const selectedModel =
input.modelSelection !== undefined && input.modelSelection.instanceId === boundInstanceId
Expand All @@ -5592,6 +5596,31 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const modelSelection = selectedModel
? { ...selectedModel, model: resolveClaudeModelSlug(modelCatalog, selectedModel.model) }
: undefined;
// Re-scan on every send: skills can change mid-session. Prepare the prompt
// before publishing a turn boundary or changing recovery state, since an
// attachment read can fail without any input reaching the SDK.
const skills = yield* discoverClaudeSkills(
claudeSettings,
context.session.cwd,
claudeEnvironment,
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
modelCatalog,
skillNames: new Set(
skills
.filter((skill) => skill.enabled && skill.userInvocable !== false)
.map((skill) => skill.name),
),
});
yield* requireCurrentContext;
invalidateExactHistory(context);
yield* updateResumeCursor(context);
if (modelSelection) {
context.startInput = { ...context.startInput, modelSelection };
}
Expand Down Expand Up @@ -5646,6 +5675,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}

yield* requireCurrentContext;
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
if (steeringTurnState === null) {
const turnState: ClaudeTurnState = {
Expand All @@ -5665,6 +5695,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
};

const updatedAt = yield* nowIso;
yield* requireCurrentContext;
context.turnState = turnState;
context.session = {
...context.session,
Expand All @@ -5677,6 +5708,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
};

const turnStartedStamp = yield* makeEventStamp();
yield* requireCurrentContext;
yield* offerRuntimeEvent(context.sessionIncarnationId, {
type: "turn.started",
eventId: turnStartedStamp.eventId,
Expand All @@ -5695,33 +5727,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
});
}

// Re-scan on every send: skills are added and switched off mid-session,
// and the scan is a few directory reads. A skill switched off via
// skillOverrides, or reserved for the agent with `user-invocable: false`,
// is left as prose: the CLI would answer `/name` with a notice instead of
// running it.
const skills = yield* discoverClaudeSkills(
claudeSettings,
context.session.cwd,
claudeEnvironment,
).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
boundInstanceId,
modelCatalog,
skillNames: new Set(
skills
.filter((skill) => skill.enabled && skill.userInvocable !== false)
.map((skill) => skill.name),
),
});

if (steeringTurnState === null) context.turnStartMessageIds.push(turnId);
yield* updateResumeCursor(context);
yield* requireCurrentContext;
yield* Queue.offer(context.promptQueue, {
type: "message",
message:
Expand Down
Loading