From 8bcf140e039e30796632c38853e8dcfaaff39188 Mon Sep 17 00:00:00 2001 From: AppLoidx <32590754+AppLoidx@users.noreply.github.com> Date: Fri, 30 Oct 2026 14:01:18 +0400 Subject: [PATCH] fix: Claude Stop-hook continuations no longer hide the answer When a Claude Stop hook blocks the end of a turn, Claude replies to the hook in the same run, and the timeline folded the real answer under "Worked for". The Claude adapter now shows the hook's feedback as a notification, and web and mobile keep the answer before it visible. --- apps/mobile/src/lib/threadActivity.test.ts | 39 +++++++++++ apps/mobile/src/lib/threadActivity.ts | 19 +++++- .../Adapters/ClaudeAdapterV2.test.ts | 62 ++++++++++++++++- .../Adapters/ClaudeAdapterV2.ts | 57 ++++++++++++++++ .../chat/MessagesTimeline.logic.test.ts | 68 +++++++++++++++++++ .../components/chat/MessagesTimeline.logic.ts | 38 ++++++++++- packages/contracts/src/orchestrationV2.ts | 2 + 7 files changed, 281 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 409631131c058..5eb2ede359033 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -849,6 +849,45 @@ describe("buildThreadFeed", () => { label: "Worked for 2s", }); + const hook: OrchestrationV2TurnItem = { + ...base("stop-hook", "2026-06-20T00:00:02.800Z", 4), + type: "notification", + source: { kind: "system" }, + outcome: "updated", + summary: "Stop hook asked Claude to continue", + detail: "[./check.sh]: Run the formatter before finishing.", + }; + const secondAnswer = { + ...assistantMessage("2026-06-20T00:00:02.900Z"), + id: TurnItemId.make("item-second"), + messageId: MessageId.make("message-second"), + text: "The formatter has run.", + }; + const secondHook = { + ...hook, + ...base("stop-hook-2", "2026-06-20T00:00:02.950Z", 6), + }; + const hookFeed = buildThreadFeed([ + projected(userMessage(), 0), + projected(opening, 1), + projected(middle, 2), + projected(command("2026-06-20T00:00:02.600Z"), 3), + projected(hook, 4), + projected(secondAnswer, 5), + projected(secondHook, 6), + projected(assistantMessage(), 7), + ]); + const hookRows = deriveThreadFeedPresentation(hookFeed, latestRun, new Set()); + expect(hookRows.map((entry) => entry.id)).toEqual([ + "message-user", + "run-fold:run-1", + "message-middle", + "local:thread-1:stop-hook", + "message-second", + "local:thread-1:stop-hook-2", + "message-assistant", + ]); + const expanded = deriveThreadFeedPresentation(feed, latestRun, new Set([runId])); expect(expanded.map((entry) => entry.type)).toEqual([ "message", diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index bd7af44b2fa07..1851c42c050f2 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -52,7 +52,13 @@ import type { ScheduledTaskId, TurnItemId, } from "@t3tools/contracts"; -import { idleCompactionOf, isCompactionCommandMessage, RunId, ThreadId } from "@t3tools/contracts"; +import { + CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY, + idleCompactionOf, + isCompactionCommandMessage, + RunId, + ThreadId, +} from "@t3tools/contracts"; import { classifyToolActivity, collectToolFilePaths, @@ -1067,6 +1073,7 @@ function deriveThreadFeedRunFolds( feedFailedRunIds: ReadonlySet, ): ReadonlyMap { const terminalAssistantMessageIdByRun = new Map(); + const stopHookAssistantMessageIds = new Set(); const interruptedRunIds = new Set(); const failedRunIds = new Set(feedFailedRunIds); const promptIndexByRunId = new Map(); @@ -1123,6 +1130,15 @@ function deriveThreadFeedRunFolds( if (entry.type !== "activity-group") continue; for (const activity of entry.activities) { const item = activity.projectedItem.item; + if ( + item.type === "notification" && + item.source.kind === "system" && + item.summary === CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY && + item.runId === runId + ) { + const answerId = terminalAssistantMessageIdByRun.get(runId); + if (answerId !== undefined) stopHookAssistantMessageIds.add(answerId); + } if (item.type === "run_interrupt_result") interruptedRunIds.add(runId); if ( runId === runlessKey && @@ -1153,6 +1169,7 @@ function deriveThreadFeedRunFolds( .filter( (entry) => entry.id !== terminalAssistantId && + !stopHookAssistantMessageIds.has(entry.id) && entry.type !== "html-render" && entry.type !== "mcp-app" && !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) && diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 40f33b3a1a309..64ceb1d77af59 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -15070,7 +15070,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { uuid, session_id: WAKE_NATIVE_SESSION, }); - const stopHookFeedback = (uuid: string, condition: string, reason: string) => + const stopHookFeedback = (uuid: string | undefined, condition: string, reason: string) => claudeSdkFrame({ type: "user", message: { @@ -15089,6 +15089,61 @@ describe("ClaudeAdapterV2 background wake turns", () => { : [], ); + it.effect.each([ + { activeGoal: false, uuid: "stop-hook" }, + { activeGoal: true, uuid: "stop-hook" }, + { activeGoal: false, uuid: undefined }, + ])( + "shows non-goal Stop hook feedback in the current run, active goal=$activeGoal, uuid=$uuid", + ({ activeGoal, uuid }) => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("stop-hook-attempt"), + text: "Check the changes.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + if (activeGoal) { + yield* Queue.offer( + harness.sdkMessages, + syntheticFrame("goal-set", "Goal set: all tests pass"), + ); + } + for (const frame of [ + makeAssistantTextFrame({ uuid: "answer", text: "Here is the answer." }), + stopHookFeedback(uuid, "./check.sh", "Run the formatter before finishing."), + makeAssistantTextFrame({ uuid: "reply", text: "The formatter has run." }), + makeResultFrame({ uuid: "result", result: "The formatter has run." }), + ]) { + yield* Queue.offer(harness.sdkMessages, frame); + } + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "completed"); + const notices = harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "notification" + ? [event.turnItem] + : [], + ); + assert.lengthOf(notices, 1); + assert.deepInclude(notices[0], { + type: "notification", + runId: input.runId, + status: "completed", + source: { kind: "system" }, + summary: "Stop hook asked Claude to continue", + detail: "[./check.sh]: Run the formatter before finishing.", + }); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + it.effect("tracks a /goal through unmet checks until Claude stops on its own", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; @@ -15114,6 +15169,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { } const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "completed"); + assert.isFalse( + harness.events.some( + (event) => event.type === "turn_item.updated" && event.turnItem.type === "notification", + ), + ); assert.deepEqual(goalStatuses(harness.events), [ { objective: condition, status: "active", checks: 0 }, { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 428e44e19020c..8bf330b7a4dbe 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -66,6 +66,7 @@ import { formatClaudeResumeCompactionQuestion, } from "@t3tools/shared/claudeCompaction"; import { + CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY, type ChatAttachment, PROVIDER_SEND_TURN_MAX_FILE_BYTES, ClaudeSettings, @@ -8220,6 +8221,62 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* liveQuery.query.close.pipe(Effect.ignore); return; } + if ( + message.type === "user" && + message.parent_tool_use_id === null && + message.isSynthetic === true && + nextClaudeGoal(goalsByNativeThread.get(liveQuery.nativeThreadId) ?? null, message) === + undefined + ) { + const content = message.message.content; + const text = + typeof content === "string" + ? content + : content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join(""); + const prefix = "Stop hook feedback:\n"; + if (text.startsWith(prefix)) { + const now = yield* DateTime.now; + const nativeItemId = + message.uuid ?? + (yield* crypto + .randomUUIDv4() + .pipe( + Effect.mapError((cause) => queryRunnerError(cause, "allocateStopHookItemId")), + )); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CLAUDE_PROVIDER, + turnItem: { + id: idAllocator.derive.turnItemFromProviderItem({ + driver: CLAUDE_PROVIDER, + nativeItemId, + }), + threadId: context.input.threadId, + runId: context.input.runId, + nodeId: context.input.rootNodeId, + providerThreadId: context.input.providerThread.id, + providerTurnId: context.providerTurnId, + nativeItemRef: { + driver: CLAUDE_PROVIDER, + nativeId: nativeItemId, + strength: message.uuid === undefined ? "weak" : "strong", + }, + parentItemId: null, + ordinal: yield* resolveItemOrdinal(context, nativeItemId), + type: "notification", + status: "completed", + title: CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY, + source: { kind: "system" }, + outcome: "updated", + summary: CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY, + detail: text.slice(prefix.length).trim(), + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }); + } + } yield* trackClaudeGoal({ nativeThreadId: liveQuery.nativeThreadId, context, message }); if (message.type === "stream_event" && !message.parent_tool_use_id) { diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index bd74694dc46af..eeb0b005a2076 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -2588,6 +2588,74 @@ describe("v2 run and attempt history", () => { "assistant-final-entry", ]); + const hook = { + id: "stop-hook", + kind: "work" as const, + createdAt: "2026-01-01T00:00:09.500Z", + entry: { + id: "stop-hook", + createdAt: "2026-01-01T00:00:09.500Z", + runId: "turn-1" as never, + label: "Stop hook asked Claude to continue", + tone: "info" as const, + itemType: "notification" as const, + structuredPayload: { + type: "notification", + source: { kind: "system" }, + summary: "Stop hook asked Claude to continue", + detail: "[./check.sh]: Run the formatter before finishing.", + } as never, + }, + }; + const secondAnswer = { + id: "assistant-second-entry", + kind: "message" as const, + createdAt: "2026-01-01T00:00:12Z", + message: { + id: "assistant-second" as never, + role: "assistant" as const, + text: "The formatter has run.", + runId: "turn-1" as never, + createdAt: "2026-01-01T00:00:12Z", + updatedAt: "2026-01-01T00:00:12Z", + streaming: false, + }, + }; + const secondHook = { + ...hook, + id: "stop-hook-2", + createdAt: "2026-01-01T00:00:15Z", + entry: { ...hook.entry, id: "stop-hook-2", createdAt: "2026-01-01T00:00:15Z" }, + }; + const hookRows = deriveMessagesTimelineRows({ + timelineEntries: [ + ...timelineEntries.slice(0, 4), + hook, + ...timelineEntries.slice(4, -1), + secondAnswer, + secondHook, + timelineEntries.at(-1)!, + ], + isWorking: false, + turnDiffSummaries: [], + supportsConversationRollback: false, + }); + expect(hookRows.map((row) => row.id)).toEqual([ + "user-entry", + "turn-fold:turn-1", + "assistant-thought-entry", + "stop-hook", + "thread-created-entry", + "assistant-second-entry", + "stop-hook-2", + "assistant-final-entry", + ]); + expect( + hookRows + .filter((row) => row.kind === "message" && row.message.role === "assistant") + .map((row) => row.kind === "message" && row.showAssistantMeta), + ).toEqual([false, false, true]); + const expandedRows = deriveMessagesTimelineRows({ timelineEntries, expandedRunIds: new Set(["turn-1" as never]), diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.ts index c26bcf51a718a..5ccb878906706 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts @@ -48,6 +48,7 @@ import { type TurnDiffSummary, } from "../../types"; import { + CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY, idleCompactionOf, isCompactionCommandMessage, type MessageId, @@ -674,6 +675,31 @@ export function resolveAssistantMessageCopyState({ }; } +function timelineEntryIsStopHook(entry: TimelineEntry): boolean { + if (entry.kind !== "work") return false; + const item = entry.entry.structuredPayload; + return ( + item?.type === "notification" && + item.source.kind === "system" && + item.summary === CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY + ); +} + +function deriveStopHookAnswerIds(timelineEntries: ReadonlyArray) { + const lastAssistantMessageIdByRun = new Map(); + const stopHookAnswerIds = new Set(); + for (const entry of timelineEntries) { + if (entry.kind === "message" && entry.message.role === "assistant" && entry.message.runId) { + lastAssistantMessageIdByRun.set(entry.message.runId, entry.message.id); + } else if (timelineEntryIsStopHook(entry)) { + const runId = timelineEntryRunId(entry); + const answerId = runId === null ? undefined : lastAssistantMessageIdByRun.get(runId); + if (answerId !== undefined) stopHookAnswerIds.add(answerId); + } + } + return stopHookAnswerIds; +} + function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray) { const lastAssistantMessageIdByResponseKey = new Map(); let nullTurnResponseIndex = 0; @@ -896,7 +922,9 @@ function timelineEntryIsSteer(entry: TimelineEntry): boolean { function timelineEntryStartsResponse(entry: TimelineEntry): boolean { return ( (entry.kind === "message" && entry.message.role === "user" && !timelineEntryIsSteer(entry)) || - (entry.kind === "work" && entry.entry.itemType === "notification") + (entry.kind === "work" && + entry.entry.itemType === "notification" && + !timelineEntryIsStopHook(entry)) ); } @@ -994,6 +1022,7 @@ function itemizedFailedRunIds( function deriveTurnFolds(input: { timelineEntries: ReadonlyArray; terminalAssistantMessageIds: ReadonlySet; + stopHookAnswerIds: ReadonlySet; latestRun: TimelineLatestRun | null; unfoldedRunIds: ReadonlySet; runlessWorkActive: boolean; @@ -1114,7 +1143,10 @@ function deriveTurnFolds(input: { ? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id) : group.entries.length; for (const [index, entry] of group.entries.entries()) { - if (entry.id === group.terminalEntry?.id) { + if ( + entry.id === group.terminalEntry?.id || + (entry.kind === "message" && input.stopHookAnswerIds.has(entry.message.id)) + ) { continue; } const isCompaction = timelineEntryIsCompaction(entry); @@ -1375,6 +1407,7 @@ function deriveTimelineTurnFolds( return deriveTurnFolds({ timelineEntries, terminalAssistantMessageIds: deriveTerminalAssistantMessageIds(timelineEntries), + stopHookAnswerIds: deriveStopHookAnswerIds(timelineEntries), latestRun: input.latestRun ?? null, unfoldedRunIds: new Set([...activeVisualResponseRunIds, ...failedRunIds]), runlessWorkActive: input.isWorking && input.runlessWorkActive === true, @@ -1449,6 +1482,7 @@ export function deriveMessagesTimelineRows(input: { const foldsByAnchorEntryId = deriveTurnFolds({ timelineEntries: timelineEntries, terminalAssistantMessageIds, + stopHookAnswerIds: deriveStopHookAnswerIds(timelineEntries), latestRun: input.latestRun ?? null, unfoldedRunIds: new Set([...activeVisualResponseRunIds, ...failedRunIds]), runlessWorkActive, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index d20da5780255b..64cc99bece56b 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1245,6 +1245,8 @@ export const OrchestrationV2NotificationSource = kindUnionWithFallback( ); export type OrchestrationV2NotificationSource = typeof OrchestrationV2NotificationSource.Type; +export const CLAUDE_STOP_HOOK_CONTINUATION_SUMMARY = "Stop hook asked Claude to continue"; + export const OrchestrationV2Notification = Schema.Struct({ source: OrchestrationV2NotificationSource, outcome: Schema.Literals(["completed", "failed", "cancelled", "updated", "unknown"]),