TypeScript
fix(claude): mid-sentence skill chips keep the full request (#15253)
Scott Norteman2b00ab167944
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex d9bf5007f7e..6b936c01fe8 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -1601,153 +1601,189 @@ describe("ClaudeAdapterV2 resume compaction", () => {});describe("ClaudeAdapterV2 attachments", () => {- it.effect("forwards images and references generic files on sends and steering", () =>- Effect.scoped(- Effect.gen(function* () {- const fileSystem = yield* FileSystem.FileSystem;- const idAllocator = yield* IdAllocator.IdAllocatorV2;- const path = yield* Path.Path;- const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({- prefix: "t3-claude-v2-attachments-",- });- const offeredMessages: Array<SDKUserMessage> = [];- const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({- instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,- settings: DEFAULT_CLAUDE_SETTINGS,- environment: {},- attachmentsDir,- fileSystem,- path: yield* Path.Path,- crypto: yield* Crypto.Crypto,- idAllocator,- queryRunner: {- allocateSessionId: Effect.succeed("native-thread-claude-attachments"),- open: () =>- Effect.succeed({- messages: Stream.never,- offer: (message) =>- Effect.sync(() => {- offeredMessages.push(message);- }),- setModel: () => Effect.void,- applyFlagSettings: () => Effect.void,- setPermissionMode: () => Effect.void,- backgroundTasks: () => Effect.succeed(false),- stopTask: () => Effect.void,- interrupt: Effect.void,- close: Effect.void,- }),- forkSession: () => Effect.die("unused forkSession"),- subagentLaunchToolUseId: () => Effect.succeed(null),- assertComplete: Effect.void,- },- });- const threadId = ThreadId.make("thread-claude-attachments");- const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments");- const runtime = yield* adapter.openSession({- threadId,- providerSessionId,- modelSelection: CLAUDE_TEST_MODEL_SELECTION,- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,- });- const providerThread = yield* runtime.ensureThread({- threadId,- modelSelection: CLAUDE_TEST_MODEL_SELECTION,- runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,- });- const attachment = ChatImageAttachment.make({- type: "image",- id: ChatAttachmentId.make(- "thread-claude-attachments-12345678-1234-1234-1234-123456789abc",- ),- name: "diagram.png",- mimeType: "image/png",- sizeBytes: 4,- });- const document = ChatFileAttachment.make({- type: "file",- id: ChatAttachmentId.make(- "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc",- ),- name: "requirements.pdf",- mimeType: "application/pdf",- sizeBytes: 4,- });- yield* fileSystem.writeFile(- path.join(attachmentsDir, attachmentRelativePath(attachment)!),- Uint8Array.from([1, 2, 3, 4]),- );- yield* fileSystem.writeFile(- path.join(attachmentsDir, attachmentRelativePath(document)!),- Uint8Array.from([5, 6, 7, 8]),- );- const attemptId = RunAttemptId.make("attempt-claude-attachments");- const now = yield* DateTime.now;-- yield* runtime.startTurn(- makeClaudeTestTurnInput({+ it.effect.each([+ {+ name: "ordinary text",+ prompt: "What’s in this image?",+ expectedText: "Ultrathink:\nWhat’s in this image?",+ command: undefined,+ ultrathink: true,+ },+ {+ name: "mid-sentence skill",+ prompt: "please $implement fixes\n\nThen report the result",+ expectedText: "Ultrathink:\nplease /implement fixes\n\nThen report the result",+ command: "/implement fixes\n\nThen report the result",+ ultrathink: true,+ },+ {+ name: "prompt-leading skill",+ prompt: "$implement fixes",+ expectedText: "/implement fixes",+ command: undefined,+ ultrathink: false,+ },+ ])(+ "preserves $name with images and files on sends and steering",+ ({ prompt, expectedText, command, ultrathink }) =>+ Effect.scoped(+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const idAllocator = yield* IdAllocator.IdAllocatorV2;+ const path = yield* Path.Path;+ const claudeHome = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-claude-v2-skills-home-",+ });+ yield* fileSystem.makeDirectory(path.join(claudeHome, "skills", "implement"), {+ recursive: true,+ });+ yield* fileSystem.writeFileString(+ path.join(claudeHome, "skills", "implement", "SKILL.md"),+ "---\ndescription: Implement the requested change\n---\nImplement it.\n",+ );+ const modelSelection = {+ ...CLAUDE_TEST_MODEL_SELECTION,+ options: ultrathink ? CLAUDE_TEST_MODEL_SELECTION.options : [],+ };+ const attachmentsDir = yield* fileSystem.makeTempDirectoryScoped({+ prefix: "t3-claude-v2-attachments-",+ });+ const offeredMessages: Array<SDKUserMessage> = [];+ const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({+ instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID,+ settings: { ...DEFAULT_CLAUDE_SETTINGS, homePath: claudeHome },+ environment: {},+ attachmentsDir,+ fileSystem,+ path: yield* Path.Path,+ crypto: yield* Crypto.Crypto,+ idAllocator,+ queryRunner: {+ allocateSessionId: Effect.succeed("native-thread-claude-attachments"),+ open: () =>+ Effect.succeed({+ messages: Stream.never,+ offer: (message) =>+ Effect.sync(() => {+ offeredMessages.push(message);+ }),+ setModel: () => Effect.void,+ applyFlagSettings: () => Effect.void,+ setPermissionMode: () => Effect.void,+ backgroundTasks: () => Effect.succeed(false),+ stopTask: () => Effect.void,+ interrupt: Effect.void,+ close: Effect.void,+ }),+ forkSession: () => Effect.die("unused forkSession"),+ subagentLaunchToolUseId: () => Effect.succeed(null),+ assertComplete: Effect.void,+ },+ });+ const threadId = ThreadId.make("thread-claude-attachments");+ const providerSessionId = ProviderSessionId.make("provider-session-claude-attachments");+ const runtime = yield* adapter.openSession({threadId,- providerThread,- now,- attemptId,- text: "What's in this image?",- attachments: [attachment, document],- }),- );+ providerSessionId,+ modelSelection,+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,+ });+ const providerThread = yield* runtime.ensureThread({+ threadId,+ modelSelection,+ runtimePolicy: CLAUDE_TEST_RUNTIME_POLICY,+ });+ const attachment = ChatImageAttachment.make({+ type: "image",+ id: ChatAttachmentId.make(+ "thread-claude-attachments-12345678-1234-1234-1234-123456789abc",+ ),+ name: "diagram.png",+ mimeType: "image/png",+ sizeBytes: 4,+ });+ const document = ChatFileAttachment.make({+ type: "file",+ id: ChatAttachmentId.make(+ "thread-claude-attachments-abcdefab-1234-1234-1234-123456789abc",+ ),+ name: "requirements.pdf",+ mimeType: "application/pdf",+ sizeBytes: 4,+ });+ yield* fileSystem.writeFile(+ path.join(attachmentsDir, attachmentRelativePath(attachment)!),+ Uint8Array.from([1, 2, 3, 4]),+ );+ yield* fileSystem.writeFile(+ path.join(attachmentsDir, attachmentRelativePath(document)!),+ Uint8Array.from([5, 6, 7, 8]),+ );+ const attemptId = RunAttemptId.make("attempt-claude-attachments");+ const now = yield* DateTime.now;- const expectedImageBlock = {- type: "image",- source: {- type: "base64",- media_type: "image/png",- data: "AQIDBA==",- },- } as const;- const expectedAttachmentPath = path.join(- attachmentsDir,- attachmentRelativePath(attachment)!,- );- const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);- assert.deepEqual(offeredMessages[0]?.message.content, [- expectedImageBlock,- {- type: "text",- text: `Ultrathink:\nWhat's in this image?\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`,- },- ]);+ yield* runtime.startTurn(+ makeClaudeTestTurnInput({+ threadId,+ providerThread,+ now,+ attemptId,+ modelSelection,+ text: prompt,+ attachments: [attachment, document],+ }),+ );- const providerTurnId = idAllocator.derive.providerTurn({- driver: ClaudeAdapterV2.CLAUDE_PROVIDER,- nativeTurnId: `turn:${attemptId}`,- });- yield* runtime.steerTurn({- threadId,- runId: RunId.make("run-claude-attachments"),- providerThread,- providerTurnId,- message: {- createdBy: "user",- creationSource: "web",- messageId: MessageId.make("message-claude-attachments-steer"),- text: "Focus on the diagram labels.",- attachments: [attachment, document],- },- });+ const expectedImageBlock = {+ type: "image",+ source: {+ type: "base64",+ media_type: "image/png",+ data: "AQIDBA==",+ },+ } as const;+ const expectedAttachmentPath = path.join(+ attachmentsDir,+ attachmentRelativePath(attachment)!,+ );+ const expectedDocumentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);+ const attachmentNotes = `\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`;+ const requestBlock = { type: "text" as const, text: expectedText + attachmentNotes };+ const expectedContent = command+ ? [+ requestBlock,+ expectedImageBlock,+ { type: "text" as const, text: command + attachmentNotes },+ ]+ : [expectedImageBlock, requestBlock];+ assert.deepEqual(offeredMessages[0]?.message.content, expectedContent);- assert.equal(offeredMessages[1]?.priority, "now");- assert.deepEqual(offeredMessages[1]?.message.content, [- expectedImageBlock,- {- type: "text",- text: `Ultrathink:\nFocus on the diagram labels.\n\n[Attached image "diagram.png" is saved at: ${expectedAttachmentPath}]\n\n[Attached file "requirements.pdf" is saved at: ${expectedDocumentPath}]`,- },- ]);- }).pipe(- Effect.provide(- Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ const providerTurnId = idAllocator.derive.providerTurn({+ driver: ClaudeAdapterV2.CLAUDE_PROVIDER,+ nativeTurnId: `turn:${attemptId}`,+ });+ yield* runtime.steerTurn({+ threadId,+ runId: RunId.make("run-claude-attachments"),+ providerThread,+ providerTurnId,+ message: {+ createdBy: "user",+ creationSource: "web",+ messageId: MessageId.make("message-claude-attachments-steer"),+ text: prompt,+ attachments: [attachment, document],+ },+ });++ assert.equal(offeredMessages[1]?.priority, "now");+ assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),),),- ),);it.effect("rejects unsupported image types before opening a provider query", () =>diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 992215dd35f..5a211e37054 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -1596,9 +1596,10 @@ export function makeClaudeUserMessage(input: {readonly uuid?: SDKUserMessage["uuid"];}): SDKUserMessage {// Claude Code expands a skill only from the LAST text block, and only when- // `/name` is its first character. A `$skill` chip anywhere in the prompt is- // therefore split into [leading text, "/name trailing text"] so the CLI runs- // it natively and the prose around it survives.+ // `/name` is its first character. A `$skill` chip anywhere in the prompt+ // therefore becomes [whole request, "/name trailing text"] so the CLI runs+ // it natively and the model still reads the full request. See+ // ClaudeSkillDispatch.const dispatch =input.skillNames === undefined? undefineddiff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.tsindex abb80482a26..0b09f6d5946 100644--- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts+++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.test.ts@@ -10,9 +10,9 @@ describe("planClaudeSkillDispatch", () => {expect(planClaudeSkillDispatch("echo $HOME then $unknown", SKILLS)).toBeUndefined();});- it("moves a mid-prompt mention into a trailing slash command", () => {+ it("keeps the whole request ahead of a mid-prompt slash command", () => {expect(planClaudeSkillDispatch("ok, now $implement all the tickets", SKILLS)).toEqual({- leadingText: "ok, now",+ leadingText: "ok, now /implement all the tickets",commandText: "/implement all the tickets",skillName: "implement",});@@ -28,7 +28,7 @@ describe("planClaudeSkillDispatch", () => {it("dispatches a known skill whose name begins with a digit", () => {expect(planClaudeSkillDispatch("use $2spec for this", SKILLS)).toEqual({- leadingText: "use",+ leadingText: "use /2spec for this",commandText: "/2spec for this",skillName: "2spec",});@@ -36,7 +36,7 @@ describe("planClaudeSkillDispatch", () => {it("dispatches the last mention and rewrites earlier ones inline", () => {expect(planClaudeSkillDispatch("$review the diff, then $implement the fixes", SKILLS)).toEqual({- leadingText: "/review the diff, then",+ leadingText: "/review the diff, then /implement the fixes",commandText: "/implement the fixes",skillName: "implement",});@@ -50,7 +50,7 @@ describe("planClaudeSkillDispatch", () => {SKILLS,),).toEqual({- leadingText: "/review the diff, then",+ leadingText: "/review the diff, then /implement the fixes",commandText: "/implement the fixes",skillName: "implement",});diff --git a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.tsindex dac74b36c20..5ab1c074493 100644--- a/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts+++ b/apps/server/src/provider/Drivers/ClaudeSkillDispatch.ts@@ -15,6 +15,7 @@ const SKILL_MENTION_PATTERN =/(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;export interface ClaudeSkillDispatch {+ /** The whole prompt with mentions as `/name`, or `undefined` when the mention opens it. */readonly leadingText: string | undefined;/** `/name` plus the trailing text, ready to be the message's last text block. */readonly commandText: string;@@ -36,19 +37,18 @@ export function planClaudeSkillDispatch(return undefined;}- const leading = prompt.slice(0, last.start);const trailing = prompt.slice(last.end);- const leadingWithInlineSlashes = mentions- .slice(0, -1)+ const promptWithInlineSlashes = mentions.reduceRight((text, mention) =>`${text.slice(0, mention.start)}/${mention.name}${text.slice(mention.end)}`,- leading,+ prompt,).trimEnd();return {- leadingText: leadingWithInlineSlashes.length > 0 ? leadingWithInlineSlashes : undefined,+ leadingText:+ prompt.slice(0, last.start).trim().length > 0 ? promptWithInlineSlashes : undefined,commandText: `/${last.name}${trailing}`.trimEnd(),skillName: last.name,};