feat(chat): show provider thinking traces (#11784)
Co-authored-by: maria-rcks <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Cursor <[email protected]>
This commit is contained in:
32 files changed
+1923
-117
No files matched your search
@@ -1,4 +1,12 @@
|
||||
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
|
||||
import {
|
||||
EnvironmentId,
|
||||
ThreadId,
|
||||
ProjectId,
|
||||
ProviderInstanceId,
|
||||
MessageId,
|
||||
type OrchestrationThreadDetailSnapshot,
|
||||
type VcsListRefsResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
@@ -69,6 +77,80 @@ function makeDatabase() {
|
||||
}
|
||||
|
||||
describe("mobile SQLite environment cache store", () => {
|
||||
it.effect(
|
||||
"invalidates pre-thinking thread caches while preserving current snapshots and other caches",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
|
||||
const now = "2026-09-04T00:00:00.000Z";
|
||||
const snapshot: OrchestrationThreadDetailSnapshot = {
|
||||
snapshotSequence: 2,
|
||||
thread: {
|
||||
id: ThreadId.make("thread-1"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
pullRequests: [],
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
deletedAt: null,
|
||||
messages: [
|
||||
{
|
||||
id: MessageId.make("thinking-1"),
|
||||
role: "reasoning",
|
||||
text: "Checking the evidence.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
page: { beforeCursor: null, hasMore: false, snapshotSequence: 2, threadSequence: 2 },
|
||||
};
|
||||
yield* store.saveThread(ENVIRONMENT_ID, snapshot);
|
||||
yield* store.saveVcsRefs(ENVIRONMENT_ID, "/repo", REFS);
|
||||
expect(yield* store.loadThread(ENVIRONMENT_ID, snapshot.thread.id)).toEqual(
|
||||
Option.some(snapshot),
|
||||
);
|
||||
const id = cacheId(ENVIRONMENT_ID, "thread", snapshot.thread.id);
|
||||
memory.values.set(
|
||||
id,
|
||||
JSON.stringify({
|
||||
schemaVersion: 3,
|
||||
environmentId: ENVIRONMENT_ID,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot: {
|
||||
...snapshot,
|
||||
thread: {
|
||||
...snapshot.thread,
|
||||
messages: snapshot.thread.messages.map((message) => ({
|
||||
...message,
|
||||
role: "system",
|
||||
})),
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(yield* store.loadThread(ENVIRONMENT_ID, snapshot.thread.id)).toEqual(Option.none());
|
||||
expect(memory.removed).toEqual([id]);
|
||||
expect(yield* store.loadVcsRefs(ENVIRONMENT_ID, "/repo")).toEqual(Option.some(REFS));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("round-trips schema-validated VCS refs", () =>
|
||||
Effect.gen(function* () {
|
||||
const memory = makeDatabase();
|
||||
|
||||
@@ -21,7 +21,9 @@ const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
// v4 reloads pre-thinking caches whose system-role fallback would otherwise
|
||||
// survive afterSequence resume and hide settled reasoning messages.
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 4;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -144,6 +144,7 @@ import {
|
||||
} from "@t3tools/mobile-markdown-text/links";
|
||||
import {
|
||||
deriveThreadFeedPresentation,
|
||||
deriveUnsettledTurnId,
|
||||
isContextCompactionActivityGroup,
|
||||
type ThreadFeedEntry,
|
||||
type ThreadFeedLatestTurn,
|
||||
@@ -158,6 +159,7 @@ import {
|
||||
collapsedWorkLogHeight,
|
||||
ThreadAgentSpawnCard,
|
||||
ThreadDisclosureChevron,
|
||||
ThreadReasoningRow,
|
||||
ThreadWorkGroupToggle,
|
||||
ThreadThinkingRow,
|
||||
ThreadWorkLog,
|
||||
@@ -193,6 +195,9 @@ import {
|
||||
ThreadMarkdownImageView,
|
||||
} from "./ThreadMarkdownImage";
|
||||
|
||||
/** `ml-7` gutter plus the `px-3` padding of the expanded reasoning container. */
|
||||
const REASONING_CONTENT_INSET = 52;
|
||||
|
||||
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
|
||||
// Native iOS blockquotes and adjacent selectable text are separate layout
|
||||
// chunks. Giving their shrink-to-fit bubble a definite width keeps both
|
||||
@@ -1348,14 +1353,17 @@ function renderFeedEntry(
|
||||
> & {
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedReasoningMessageIds: ReadonlySet<string>;
|
||||
readonly workRowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
|
||||
readonly workGroupScrollPositions: Map<string, ThreadWorkGroupScrollPosition>;
|
||||
readonly terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
readonly unsettledTurnId: TurnId | null;
|
||||
readonly isWorking: boolean;
|
||||
readonly onCopyWorkRow: (rowId: string, value: string) => void;
|
||||
readonly onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
|
||||
readonly onToggleWorkRow: (rowId: string, anchorKey: string) => void;
|
||||
readonly onToggleTurnFold: (turnId: TurnId) => void;
|
||||
readonly onToggleReasoning: (messageId: string) => void;
|
||||
readonly onPressPreview: (source: FilePreviewSource) => void;
|
||||
readonly onPressVideo: (attachment: ChatFileAttachment, sourceIdentifier: string) => void;
|
||||
readonly markdownLinkHandlers: MarkdownLinkHandlers;
|
||||
@@ -1467,6 +1475,38 @@ function renderFeedEntry(
|
||||
|
||||
if (entry.type === "message") {
|
||||
const { message } = entry;
|
||||
if (message.role === "reasoning") {
|
||||
// Only the live turn may claim to still be thinking, and only while the
|
||||
// thread is actually working: a block left open by a crashed provider
|
||||
// must not shimmer on a turn that settled long ago. Same test as web.
|
||||
const liveReasoning =
|
||||
Boolean(message.streaming) &&
|
||||
props.isWorking &&
|
||||
message.turnId !== null &&
|
||||
message.turnId === props.unsettledTurnId;
|
||||
return (
|
||||
<ThreadReasoningRow
|
||||
rowSizing={props.workRowSizing}
|
||||
iconSubtleColor={iconSubtleColor}
|
||||
expanded={props.expandedReasoningMessageIds.has(message.id)}
|
||||
label={liveReasoning ? "Thinking" : "Thought"}
|
||||
streaming={liveReasoning}
|
||||
onToggle={() => props.onToggleReasoning(message.id)}
|
||||
>
|
||||
<MarkdownImageAvailableWidthContext
|
||||
value={props.markdownContentWidth - REASONING_CONTENT_INSET}
|
||||
>
|
||||
<AssistantMarkdownContent
|
||||
markdown={message.text}
|
||||
markdownStyles={markdownStyles.assistant}
|
||||
linkHandlers={props.markdownLinkHandlers}
|
||||
renderImage={props.renderMarkdownImage}
|
||||
skills={props.skills}
|
||||
/>
|
||||
</MarkdownImageAvailableWidthContext>
|
||||
</ThreadReasoningRow>
|
||||
);
|
||||
}
|
||||
const isUser = message.role === "user";
|
||||
const renderedText = renderAssistantCitationsAsText(message.text);
|
||||
const styles = isUser ? markdownStyles.user : markdownStyles.assistant;
|
||||
@@ -1960,13 +2000,21 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
readonly expandedWorkRows: Record<string, boolean>;
|
||||
readonly expandedTurnIds: ReadonlySet<TurnId>;
|
||||
readonly expandedReasoningMessageIds: ReadonlySet<string>;
|
||||
}>({
|
||||
copiedRowId: null,
|
||||
expandedWorkGroups: {},
|
||||
expandedWorkRows: {},
|
||||
expandedTurnIds: new Set(),
|
||||
expandedReasoningMessageIds: new Set(),
|
||||
});
|
||||
const { copiedRowId, expandedWorkGroups, expandedWorkRows, expandedTurnIds } = interactionState;
|
||||
const {
|
||||
copiedRowId,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
expandedTurnIds,
|
||||
expandedReasoningMessageIds,
|
||||
} = interactionState;
|
||||
const [expandedFile, setExpandedFile] = useState<FilePreviewSource | null>(null);
|
||||
const [expandedVideo, setExpandedVideo] = useState<VideoPreviewSource | null>(null);
|
||||
const fileShareSourceIdentifier = useId();
|
||||
@@ -2218,11 +2266,9 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const markdownStyles = useMarkdownStyles(onMarkdownLinkPress, renderMarkdownImage);
|
||||
const reviewCommentColors = useReviewCommentColors();
|
||||
const unsettledTurnId =
|
||||
props.latestTurn &&
|
||||
(props.latestTurn.completedAt === null || props.latestTurn.state === "running")
|
||||
? props.latestTurn.turnId
|
||||
: null;
|
||||
// One definition of "still live", shared with the fold derivation: two
|
||||
// copies of this test are what let a row and the fold beside it disagree.
|
||||
const unsettledTurnId = deriveUnsettledTurnId(props.latestTurn ?? null);
|
||||
// LegendList does not invalidate visible rows when only the renderItem closure changes.
|
||||
// Include turn completion so unchanged message rows reveal their footer and spacing
|
||||
// even when the final message update arrives before the turn settles.
|
||||
@@ -2232,6 +2278,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
unsettledTurnId,
|
||||
copiedRowId,
|
||||
expandedWorkRows,
|
||||
expandedReasoningMessageIds,
|
||||
workRowSizing,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -2245,6 +2292,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
unsettledTurnId,
|
||||
copiedRowId,
|
||||
expandedWorkRows,
|
||||
expandedReasoningMessageIds,
|
||||
workRowSizing,
|
||||
iconSubtleColor,
|
||||
markdownStyles,
|
||||
@@ -2517,7 +2565,13 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
if (disclosureAnchorKeyRef.current !== null) {
|
||||
settleDisclosureAfterLayout();
|
||||
}
|
||||
}, [expandedTurnIds, expandedWorkGroups, expandedWorkRows, settleDisclosureAfterLayout]);
|
||||
}, [
|
||||
expandedTurnIds,
|
||||
expandedWorkGroups,
|
||||
expandedWorkRows,
|
||||
expandedReasoningMessageIds,
|
||||
settleDisclosureAfterLayout,
|
||||
]);
|
||||
|
||||
const handleItemSizeChanged = useCallback(() => {
|
||||
if (disclosureAnchorKeyRef.current !== null) {
|
||||
@@ -2600,6 +2654,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onToggleReasoning = useCallback(
|
||||
(messageId: string) => {
|
||||
// The anchor must be the feed row id, which for a message row is the
|
||||
// message id, or position restoration is skipped for every row.
|
||||
suspendEndScrollMaintenanceForDisclosure(messageId);
|
||||
setInteractionState((current) => {
|
||||
const next = new Set(current.expandedReasoningMessageIds);
|
||||
if (next.has(messageId)) {
|
||||
next.delete(messageId);
|
||||
} else {
|
||||
next.add(messageId);
|
||||
}
|
||||
return { ...current, expandedReasoningMessageIds: next };
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
const onPressPreview = useCallback((source: FilePreviewSource) => {
|
||||
setExpandedFile((current) => current ?? source);
|
||||
}, []);
|
||||
@@ -2626,6 +2698,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return undefined;
|
||||
}
|
||||
switch (entry.type) {
|
||||
case "message":
|
||||
// A collapsed reasoning row is the same chrome as a work toggle.
|
||||
return entry.message.role === "reasoning" &&
|
||||
!expandedReasoningMessageIds.has(entry.message.id)
|
||||
? WORK_GROUP_TOGGLE_HEIGHT
|
||||
: undefined;
|
||||
case "turn-fold":
|
||||
return TURN_FOLD_HEIGHT;
|
||||
case "work-toggle":
|
||||
@@ -2644,7 +2722,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
[expandedWorkRows, workRowSizing.fixedRowHeight],
|
||||
[expandedReasoningMessageIds, expandedWorkRows, workRowSizing.fixedRowHeight],
|
||||
);
|
||||
|
||||
// Disclosures can mount existing offscreen rows as well as new work rows.
|
||||
@@ -2662,14 +2740,17 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
onEditPendingMessage: props.onEditPendingMessage,
|
||||
copiedRowId,
|
||||
expandedWorkRows,
|
||||
expandedReasoningMessageIds,
|
||||
workRowSizing,
|
||||
workGroupScrollPositions,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
isWorking: props.activeWorkStartedAt !== null,
|
||||
onCopyWorkRow,
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
onToggleTurnFold,
|
||||
onToggleReasoning,
|
||||
onPressPreview,
|
||||
onPressVideo,
|
||||
markdownLinkHandlers,
|
||||
@@ -2696,10 +2777,12 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
copiedRowId,
|
||||
disclosureToggleSettling,
|
||||
expandedWorkRows,
|
||||
expandedReasoningMessageIds,
|
||||
workRowSizing,
|
||||
workGroupScrollPositions,
|
||||
terminalAssistantMessageIds,
|
||||
unsettledTurnId,
|
||||
props.activeWorkStartedAt,
|
||||
iconSubtleColor,
|
||||
screenColor,
|
||||
userBubbleColor,
|
||||
@@ -2713,6 +2796,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
markdownLinkHandlers,
|
||||
onPressPreview,
|
||||
onPressVideo,
|
||||
onToggleReasoning,
|
||||
onToggleTurnFold,
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkRow,
|
||||
|
||||
@@ -1150,6 +1150,85 @@ export function ThreadThinkingRow(props: {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider's thinking trace. Collapsed by default: reasoning is context for
|
||||
* the answer, not the answer. `expanded` lives on the feed so it survives row
|
||||
* recycling; `children` is the trace body and only mounts while open.
|
||||
*/
|
||||
export function ThreadReasoningRow(props: {
|
||||
readonly rowSizing: ReturnType<typeof deriveThreadWorkLogSizing>;
|
||||
readonly iconSubtleColor: ColorValue;
|
||||
readonly expanded: boolean;
|
||||
readonly label: string;
|
||||
readonly streaming: boolean;
|
||||
readonly onToggle: () => void;
|
||||
readonly children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<View className={cn("-mx-1 px-1 py-0", props.expanded && "pb-1.5")}>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
accessibilityState={{ expanded: props.expanded }}
|
||||
accessibilityLabel={props.label}
|
||||
accessibilityHint={`Double tap to ${props.expanded ? "hide" : "show"} the thinking trace.`}
|
||||
hitSlop={4}
|
||||
onPress={() => {
|
||||
void Haptics.selectionAsync();
|
||||
props.onToggle();
|
||||
}}
|
||||
className="min-h-8 flex-row items-center gap-1.5 rounded-md px-0.5 py-0 active:bg-subtle"
|
||||
style={{ minHeight: props.rowSizing.estimatedRowHeight }}
|
||||
>
|
||||
{props.streaming ? (
|
||||
<ShimmeringWorkContent
|
||||
key={props.rowSizing.textSizeKey}
|
||||
icon="brain"
|
||||
iconSubtleColor={props.iconSubtleColor}
|
||||
label={props.label}
|
||||
showIcon
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<View className="h-6 w-6 shrink-0 items-center justify-center">
|
||||
<WorkLogIcon icon="brain" color={props.iconSubtleColor} />
|
||||
</View>
|
||||
<Text
|
||||
key={props.rowSizing.textSizeKey}
|
||||
className="min-w-0 flex-1 text-sm text-foreground-muted"
|
||||
numberOfLines={1}
|
||||
>
|
||||
{props.label}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
<ThreadDisclosureChevron
|
||||
expanded={props.expanded}
|
||||
collapsedDirection="right"
|
||||
size={11}
|
||||
tintColor={props.iconSubtleColor}
|
||||
/>
|
||||
</Pressable>
|
||||
{props.expanded ? (
|
||||
<Animated.View
|
||||
entering={WORK_LOG_DETAIL_ENTER_TRANSITION}
|
||||
exiting={WORK_LOG_DETAIL_EXIT_TRANSITION}
|
||||
layout={WORK_LOG_LAYOUT_TRANSITION}
|
||||
className="ml-7 mt-1 rounded-xl bg-subtle px-3 py-2"
|
||||
>
|
||||
<ScrollView
|
||||
nestedScrollEnabled
|
||||
directionalLockEnabled
|
||||
showsVerticalScrollIndicator
|
||||
className="max-h-80"
|
||||
>
|
||||
{props.children}
|
||||
</ScrollView>
|
||||
</Animated.View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function ToolActivityIconView(props: {
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly icon?: ToolActivityIcon;
|
||||
|
||||
@@ -1596,7 +1596,7 @@ function maxIsoTimestamp(a: string | null, b: string | null): string | null {
|
||||
return bMs > aMs ? b : a;
|
||||
}
|
||||
|
||||
function deriveUnsettledTurnId(latestTurn: ThreadFeedLatestTurn | null): TurnId | null {
|
||||
export function deriveUnsettledTurnId(latestTurn: ThreadFeedLatestTurn | null): TurnId | null {
|
||||
if (!latestTurn) {
|
||||
return null;
|
||||
}
|
||||
@@ -1637,8 +1637,13 @@ function deriveThreadFeedTurnFolds(
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
// Thinking is work, so it folds with the rest of it. A provider that
|
||||
// interleaves a block with every tool call would otherwise leave dozens of
|
||||
// "Thought" rows standing beside the "Worked for ..." summary.
|
||||
// Nothing folds while the turn is live, which is when traces are watched.
|
||||
const turnId =
|
||||
entry.type === "message" && entry.message.role === "assistant"
|
||||
entry.type === "message" &&
|
||||
(entry.message.role === "assistant" || entry.message.role === "reasoning")
|
||||
? entry.message.turnId
|
||||
: entry.type === "activity-group"
|
||||
? entry.turnId
|
||||
@@ -1665,7 +1670,15 @@ function deriveThreadFeedTurnFolds(
|
||||
if (turnId === unsettledTurnId) {
|
||||
continue;
|
||||
}
|
||||
if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) {
|
||||
// A live turn is already excluded above, so only an answer still being
|
||||
// written may hold a fold open. A thinking block stranded by a crashed
|
||||
// provider keeps its streaming flag forever and must not.
|
||||
if (
|
||||
entries.some(
|
||||
(entry) =>
|
||||
entry.type === "message" && entry.message.streaming && entry.message.role !== "reasoning",
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1685,13 +1698,16 @@ function deriveThreadFeedTurnFolds(
|
||||
continue;
|
||||
}
|
||||
// A lone compaction row stays visible on its own; it only folds away as
|
||||
// part of a turn that already folds other work.
|
||||
const hidesNonCompactionWork = entries.some(
|
||||
// part of a turn that already folds other work. Thinking is the same: a
|
||||
// question answered by thought alone keeps its "Thought" row
|
||||
// rather than collapsing behind a "Worked for ..." that hides nothing else.
|
||||
const hidesFoldableWork = entries.some(
|
||||
(entry) =>
|
||||
hiddenEntryIds.has(entry.id) &&
|
||||
!(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
|
||||
!(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)) &&
|
||||
!(entry.type === "message" && entry.message.role === "reasoning"),
|
||||
);
|
||||
if (!hidesNonCompactionWork) {
|
||||
if (!hidesFoldableWork) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1819,6 +1835,15 @@ export function deriveThreadFeedPresentation(
|
||||
!result.some(
|
||||
(row) =>
|
||||
(row.type === "work-toggle" && row.shimmer) ||
|
||||
// A live thinking block is the real version of this row, so it takes
|
||||
// the slot instead of sitting under a second "Thinking". Scoped to the
|
||||
// live turn: a block stranded by a killed server must not silence this
|
||||
// row for every turn that follows.
|
||||
(row.type === "message" &&
|
||||
row.message.role === "reasoning" &&
|
||||
row.message.streaming &&
|
||||
row.message.turnId !== null &&
|
||||
row.message.turnId === unsettledTurnId) ||
|
||||
// A working spawn card is the live activity: its status line shows
|
||||
// what the agents are doing, so a Thinking row under it would lie.
|
||||
(row.type === "agent-spawn" &&
|
||||
|
||||
@@ -645,11 +645,17 @@ function dropSupersededToolUpdatedActivities(
|
||||
|
||||
export function projectThreadDetailSnapshot(
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
reasoningMessages = true,
|
||||
): OrchestrationThreadDetailSnapshot {
|
||||
return {
|
||||
...snapshot,
|
||||
thread: {
|
||||
...snapshot.thread,
|
||||
messages: reasoningMessages
|
||||
? snapshot.thread.messages
|
||||
: snapshot.thread.messages.map((message) =>
|
||||
message.role === "reasoning" ? { ...message, role: "system" as const } : message,
|
||||
),
|
||||
activities: dropSupersededToolUpdatedActivities(
|
||||
dropStaleContextWindowActivities(snapshot.thread.activities),
|
||||
).map(projectActivityPayload),
|
||||
@@ -657,7 +663,19 @@ export function projectThreadDetailSnapshot(
|
||||
};
|
||||
}
|
||||
|
||||
export function projectActivityEvent(event: OrchestrationEvent): OrchestrationEvent {
|
||||
export function projectActivityEvent(
|
||||
event: OrchestrationEvent,
|
||||
reasoningMessages = true,
|
||||
): OrchestrationEvent {
|
||||
// Preserve sequence watermarks and message identities for clients whose role
|
||||
// decoder predates reasoning. Filtering would strand their history pages.
|
||||
if (
|
||||
!reasoningMessages &&
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "reasoning"
|
||||
) {
|
||||
return { ...event, payload: { ...event.payload, role: "system" } };
|
||||
}
|
||||
if (event.type !== "thread.activity-appended") {
|
||||
return event;
|
||||
}
|
||||
|
||||
@@ -1056,6 +1056,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
AND threads.archived_at IS NULL
|
||||
AND projects.deleted_at IS NULL
|
||||
AND messages.is_streaming = 0
|
||||
-- Only these two roles are searchable, and the CASE above depends
|
||||
-- on it: reasoning is deliberately excluded so a thinking trace
|
||||
-- cannot surface in the command palette, and widening this filter
|
||||
-- would label it 'assistant' rather than adding a source.
|
||||
AND (
|
||||
messages.role = 'user'
|
||||
OR (
|
||||
|
||||
@@ -1345,7 +1345,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const harness = await createHarness();
|
||||
const initial = await harness.readModel();
|
||||
|
||||
for (const streamKind of ["reasoning_text", "command_output", "file_change_output"] as const) {
|
||||
for (const streamKind of ["command_output", "file_change_output"] as const) {
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId(`evt-ignored-${streamKind}`),
|
||||
@@ -1421,6 +1421,332 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(message?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("streams reasoning deltas into a finalized reasoning message", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
for (const delta of ["Weighing ", "the options"]) {
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId(`evt-reasoning-${delta.trim()}`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-reasoning"),
|
||||
itemId: asItemId("item-r1"),
|
||||
payload: { streamKind: "reasoning_text", delta },
|
||||
});
|
||||
}
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-reasoning-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-reasoning"),
|
||||
itemId: asItemId("item-r1"),
|
||||
payload: { itemType: "reasoning", status: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" &&
|
||||
!message.streaming &&
|
||||
message.text === "Weighing the options",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(message?.text).toBe("Weighing the options");
|
||||
expect(message?.streaming).toBe(false);
|
||||
expect(thread.messages.some((entry) => entry.role === "assistant")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps a reasoning summary's parts apart", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
for (const [summaryIndex, delta] of [
|
||||
[0, "**First**"],
|
||||
[1, "**Second**"],
|
||||
] as const) {
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId(`evt-summary-${summaryIndex}`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-summary"),
|
||||
itemId: asItemId("item-s1"),
|
||||
payload: { streamKind: "reasoning_summary_text", delta, summaryIndex },
|
||||
});
|
||||
}
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-summary-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-summary"),
|
||||
itemId: asItemId("item-s1"),
|
||||
payload: { itemType: "reasoning", status: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" &&
|
||||
!message.streaming &&
|
||||
message.text === "**First**\n\n**Second**",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(message?.text).toBe("**First**\n\n**Second**");
|
||||
});
|
||||
|
||||
it("uses a reasoning item's detail when no reasoning deltas were streamed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-reasoning-snapshot"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-snapshot"),
|
||||
itemId: asItemId("item-snapshot"),
|
||||
payload: {
|
||||
itemType: "reasoning",
|
||||
status: "completed",
|
||||
detail: "reasoning reported in one piece",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.readModel, (entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" &&
|
||||
!message.streaming &&
|
||||
message.text === "reasoning reported in one piece",
|
||||
),
|
||||
);
|
||||
const message = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(message?.text).toBe("reasoning reported in one piece");
|
||||
|
||||
for (const [index, detail] of ["", " \n\t"].entries()) {
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId(`evt-empty-reasoning-${index}`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId(`turn-empty-${index}`),
|
||||
itemId: asItemId(`item-empty-${index}`),
|
||||
payload: { itemType: "reasoning", status: "completed", detail },
|
||||
});
|
||||
}
|
||||
|
||||
// A repeated completion must rewrite that row, not add a second copy.
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-reasoning-snapshot-repeat"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-snapshot"),
|
||||
itemId: asItemId("item-snapshot"),
|
||||
payload: {
|
||||
itemType: "reasoning",
|
||||
status: "completed",
|
||||
detail: "reasoning reported in one piece",
|
||||
},
|
||||
});
|
||||
await harness.drain();
|
||||
const after = await harness.readModel();
|
||||
const repeated = after.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
expect(
|
||||
repeated?.messages.filter((entry: ProviderRuntimeTestMessage) => entry.role === "reasoning")
|
||||
.length,
|
||||
).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps interleaved summary and raw reasoning in separate blocks", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
// Distinct timestamps: blocks are ordered by when the provider opened them.
|
||||
for (const [tag, at, streamKind, delta] of [
|
||||
["a", "2026-01-01T00:00:01.000Z", "reasoning_summary_text", "summary one"],
|
||||
["b", "2026-01-01T00:00:02.000Z", "reasoning_text", "raw one"],
|
||||
["c", "2026-01-01T00:00:03.000Z", "reasoning_summary_text", "summary two"],
|
||||
] as const) {
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId(`evt-interleaved-${tag}`),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: at,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-interleaved"),
|
||||
itemId: asItemId("item-interleaved"),
|
||||
payload: { streamKind, delta },
|
||||
});
|
||||
}
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-interleaved-completed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-interleaved"),
|
||||
itemId: asItemId("item-interleaved"),
|
||||
payload: { itemType: "reasoning", status: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.messages.filter(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" && !message.streaming,
|
||||
).length === 3,
|
||||
);
|
||||
const reasoning = thread.messages.filter(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(reasoning.map((entry) => entry.text)).toEqual(["summary one", "raw one", "summary two"]);
|
||||
expect(new Set(reasoning.map((entry) => entry.id)).size).toBe(3);
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
"closes reasoning when the assistant answers (deltas: %s)",
|
||||
async (withDeltas) => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-think-before-answer"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-answer"),
|
||||
payload: { streamKind: "reasoning_text", delta: "thinking it through" },
|
||||
});
|
||||
if (withDeltas) {
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-answer-after-think"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-answer"),
|
||||
itemId: asItemId("item-a1"),
|
||||
payload: { streamKind: "assistant_text", delta: "the answer" },
|
||||
});
|
||||
}
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-answer-completed"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-answer"),
|
||||
itemId: asItemId("item-a1"),
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
status: "completed",
|
||||
...(!withDeltas ? { detail: "the answer" } : {}),
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" && !message.streaming,
|
||||
) &&
|
||||
entry.messages.some(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "assistant" && !message.streaming,
|
||||
),
|
||||
);
|
||||
const reasoning = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(reasoning?.text).toBe("thinking it through");
|
||||
expect(reasoning?.streaming).toBe(false);
|
||||
const assistant = thread.messages.find(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "assistant",
|
||||
);
|
||||
expect(assistant?.text).toBe("the answer");
|
||||
},
|
||||
);
|
||||
|
||||
it("starts a new reasoning block after tool work", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-think-before-tool"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tooled"),
|
||||
payload: { streamKind: "reasoning_text", delta: "before the tool" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.started",
|
||||
eventId: asEventId("evt-tool-between-thoughts"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tooled"),
|
||||
itemId: asItemId("item-tool-1"),
|
||||
payload: { itemType: "command_execution", status: "inProgress", title: "ls" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "content.delta",
|
||||
eventId: asEventId("evt-think-after-tool"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tooled"),
|
||||
payload: { streamKind: "reasoning_text", delta: "after the tool" },
|
||||
});
|
||||
harness.emit({
|
||||
type: "item.completed",
|
||||
eventId: asEventId("evt-second-thought-completed"),
|
||||
provider: ProviderDriverKind.make("claude"),
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-tooled"),
|
||||
payload: { itemType: "reasoning", status: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
harness.readModel,
|
||||
(entry) =>
|
||||
entry.messages.filter(
|
||||
(message: ProviderRuntimeTestMessage) =>
|
||||
message.role === "reasoning" && !message.streaming,
|
||||
).length === 2,
|
||||
);
|
||||
const reasoning = thread.messages.filter(
|
||||
(entry: ProviderRuntimeTestMessage) => entry.role === "reasoning",
|
||||
);
|
||||
expect(reasoning.map((entry) => entry.text)).toEqual(["before the tool", "after the tool"]);
|
||||
expect(reasoning[0]?.streaming).toBe(false);
|
||||
});
|
||||
|
||||
it("uses assistant item completion detail when no assistant deltas were streamed", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
@@ -57,6 +57,11 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
|
||||
import { canReplaceThreadTitle } from "../threadTitles.ts";
|
||||
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
// Suffixed, not prefixed: `clearTurnStateForSession` sweeps by thread prefix.
|
||||
const segmentStateKey = (threadId: ThreadId, turnId: TurnId, role: MessageStreamRole) =>
|
||||
role === "reasoning"
|
||||
? `${providerTurnKey(threadId, turnId)}:reasoning`
|
||||
: providerTurnKey(threadId, turnId);
|
||||
const providerTaskKey = (threadId: ThreadId, taskId: string) => `${threadId}:${taskId}`;
|
||||
|
||||
// Fallback when the in-memory description cache no longer has the task name
|
||||
@@ -270,11 +275,41 @@ function assistantSegmentBaseKeyFromEvent(event: ProviderRuntimeEvent): string {
|
||||
return String(event.itemId ?? event.turnId ?? event.eventId);
|
||||
}
|
||||
|
||||
function assistantSegmentMessageId(baseKey: string, segmentIndex: number): MessageId {
|
||||
/**
|
||||
* Reasoning shares the assistant segmenting, buffering and finalization
|
||||
* machinery; only the message id namespace differs. The prefix is what tells a
|
||||
* buffered segment apart when it is flushed or finalized long after the delta
|
||||
* that opened it, so the role never has to be threaded through those paths.
|
||||
*/
|
||||
type MessageStreamRole = "assistant" | "reasoning";
|
||||
|
||||
const REASONING_MESSAGE_ID_PREFIX = "reasoning:";
|
||||
|
||||
function messageStreamRoleOf(messageId: MessageId): MessageStreamRole {
|
||||
return messageId.startsWith(REASONING_MESSAGE_ID_PREFIX) ? "reasoning" : "assistant";
|
||||
}
|
||||
|
||||
function assistantSegmentMessageId(
|
||||
baseKey: string,
|
||||
segmentIndex: number,
|
||||
role: MessageStreamRole = "assistant",
|
||||
): MessageId {
|
||||
const prefix = role === "reasoning" ? REASONING_MESSAGE_ID_PREFIX : "assistant:";
|
||||
return MessageId.make(
|
||||
segmentIndex === 0 ? `assistant:${baseKey}` : `assistant:${baseKey}:segment:${segmentIndex}`,
|
||||
segmentIndex === 0 ? `${prefix}${baseKey}` : `${prefix}${baseKey}:segment:${segmentIndex}`,
|
||||
);
|
||||
}
|
||||
|
||||
/** A provider may stream a reasoning summary and the raw chain of thought over
|
||||
* the same item. They are different texts, so they get different segments. */
|
||||
function reasoningSegmentBaseKeyFromEvent(
|
||||
event: ProviderRuntimeEvent,
|
||||
streamKind: "reasoning_text" | "reasoning_summary_text",
|
||||
): string {
|
||||
const stream = streamKind === "reasoning_summary_text" ? "summary" : "raw";
|
||||
return `${stream}:${assistantSegmentBaseKeyFromEvent(event)}`;
|
||||
}
|
||||
|
||||
function buildContextWindowActivityPayload(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
@@ -1005,6 +1040,23 @@ const make = Effect.gen(function* () {
|
||||
lookup: () => Effect.succeed(0),
|
||||
});
|
||||
|
||||
// When a thinking block opened, so "Thought for ..." measures the model's
|
||||
// time and not the moment buffered text happened to be flushed.
|
||||
const reasoningStartedAtByMessageId = yield* Cache.make<MessageId, string>({
|
||||
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
|
||||
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
|
||||
lookup: () => Effect.succeed(""),
|
||||
});
|
||||
|
||||
// Codex splits a reasoning trace into indexed parts, summary and raw alike.
|
||||
// The index is the only signal that one part ended and the next began, so the
|
||||
// blank line that keeps them readable has to be inserted here.
|
||||
const reasoningPartIndexByMessageId = yield* Cache.make<MessageId, number>({
|
||||
capacity: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY,
|
||||
timeToLive: BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_TTL,
|
||||
lookup: () => Effect.succeed(-1),
|
||||
});
|
||||
|
||||
const assistantSegmentStateByTurnKey = yield* Cache.make<string, AssistantSegmentState>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
timeToLive: TURN_MESSAGE_IDS_BY_TURN_TTL,
|
||||
@@ -1104,20 +1156,31 @@ const make = Effect.gen(function* () {
|
||||
const clearAssistantMessageIdsForTurn = (threadId: ThreadId, turnId: TurnId) =>
|
||||
Cache.invalidate(turnMessageIdsByTurnKey, providerTurnKey(threadId, turnId));
|
||||
|
||||
const getAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>
|
||||
Cache.getOption(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));
|
||||
const getAssistantSegmentStateForTurn = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
role: MessageStreamRole = "assistant",
|
||||
) => Cache.getOption(assistantSegmentStateByTurnKey, segmentStateKey(threadId, turnId, role));
|
||||
|
||||
const setAssistantSegmentStateForTurn = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
state: AssistantSegmentState,
|
||||
) => Cache.set(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId), state);
|
||||
role: MessageStreamRole = "assistant",
|
||||
) => Cache.set(assistantSegmentStateByTurnKey, segmentStateKey(threadId, turnId, role), state);
|
||||
|
||||
const clearAssistantSegmentStateForTurn = (threadId: ThreadId, turnId: TurnId) =>
|
||||
Cache.invalidate(assistantSegmentStateByTurnKey, providerTurnKey(threadId, turnId));
|
||||
const clearAssistantSegmentStateForTurn = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
role: MessageStreamRole = "assistant",
|
||||
) => Cache.invalidate(assistantSegmentStateByTurnKey, segmentStateKey(threadId, turnId, role));
|
||||
|
||||
const getActiveAssistantMessageIdForTurn = (threadId: ThreadId, turnId: TurnId) =>
|
||||
getAssistantSegmentStateForTurn(threadId, turnId).pipe(
|
||||
const getActiveAssistantMessageIdForTurn = (
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
role: MessageStreamRole = "assistant",
|
||||
) =>
|
||||
getAssistantSegmentStateForTurn(threadId, turnId, role).pipe(
|
||||
Effect.map((state) =>
|
||||
Option.flatMap(state, (entry) =>
|
||||
entry.activeMessageId ? Option.some(entry.activeMessageId) : Option.none(),
|
||||
@@ -1129,31 +1192,38 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId;
|
||||
turnId: TurnId;
|
||||
baseKey: string;
|
||||
}) =>
|
||||
getAssistantSegmentStateForTurn(input.threadId, input.turnId).pipe(
|
||||
role?: MessageStreamRole;
|
||||
}) => {
|
||||
const role = input.role ?? "assistant";
|
||||
return getAssistantSegmentStateForTurn(input.threadId, input.turnId, role).pipe(
|
||||
Effect.flatMap((existingState) =>
|
||||
Effect.gen(function* () {
|
||||
const nextState = Option.match(existingState, {
|
||||
onNone: () => ({
|
||||
baseKey: input.baseKey,
|
||||
nextSegmentIndex: 1,
|
||||
activeMessageId: assistantSegmentMessageId(input.baseKey, 0),
|
||||
activeMessageId: assistantSegmentMessageId(input.baseKey, 0, role),
|
||||
}),
|
||||
onSome: (state) => {
|
||||
const segmentIndex = state.baseKey === input.baseKey ? state.nextSegmentIndex : 0;
|
||||
const messageId = assistantSegmentMessageId(input.baseKey, segmentIndex);
|
||||
// Reasoning never resets the index on a new base key: one item can
|
||||
// stream a summary and a raw trace, and summary -> raw -> summary
|
||||
// would otherwise reuse the id of the first, finished block.
|
||||
const reuseIndex = state.baseKey === input.baseKey || role === "reasoning";
|
||||
const segmentIndex = reuseIndex ? state.nextSegmentIndex : 0;
|
||||
const messageId = assistantSegmentMessageId(input.baseKey, segmentIndex, role);
|
||||
return {
|
||||
baseKey: input.baseKey,
|
||||
nextSegmentIndex: state.baseKey === input.baseKey ? state.nextSegmentIndex + 1 : 1,
|
||||
nextSegmentIndex: reuseIndex ? state.nextSegmentIndex + 1 : 1,
|
||||
activeMessageId: messageId,
|
||||
} satisfies AssistantSegmentState;
|
||||
},
|
||||
});
|
||||
yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, nextState);
|
||||
yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, nextState, role);
|
||||
return nextState.activeMessageId!;
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const getOrCreateAssistantMessageId = (input: {
|
||||
threadId: ThreadId;
|
||||
@@ -1180,6 +1250,52 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* Unlike assistant text, reasoning has no reliable per-block item id on every
|
||||
* provider, so a turn's blocks can share a base key. Switching base key (a new
|
||||
* reasoning item, or summary vs raw) closes the open block instead of
|
||||
* appending to it.
|
||||
*/
|
||||
const getOrCreateReasoningMessageId = (input: {
|
||||
threadId: ThreadId;
|
||||
event: ProviderRuntimeEvent;
|
||||
baseKey: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const state = yield* getAssistantSegmentStateForTurn(
|
||||
input.threadId,
|
||||
input.turnId,
|
||||
"reasoning",
|
||||
);
|
||||
const activeMessageId = Option.flatMap(state, (entry) =>
|
||||
entry.activeMessageId ? Option.some(entry.activeMessageId) : Option.none(),
|
||||
);
|
||||
if (Option.isSome(activeMessageId)) {
|
||||
if (Option.getOrUndefined(state)?.baseKey === input.baseKey) {
|
||||
return activeMessageId.value;
|
||||
}
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event: input.event,
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
commandTag: "reasoning-complete-on-new-block",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize-on-new-block",
|
||||
hasProjectedMessage: false,
|
||||
role: "reasoning",
|
||||
});
|
||||
}
|
||||
|
||||
return yield* startAssistantSegmentForTurn({
|
||||
threadId: input.threadId,
|
||||
turnId: input.turnId,
|
||||
baseKey: input.baseKey,
|
||||
role: "reasoning",
|
||||
});
|
||||
});
|
||||
|
||||
const resolveResponseStreamingMode = (projectId: ProjectId) =>
|
||||
Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
@@ -1270,7 +1386,15 @@ const make = Effect.gen(function* () {
|
||||
Cache.invalidate(bufferedProposedPlanById, planId);
|
||||
|
||||
const clearAssistantMessageState = (messageId: MessageId) =>
|
||||
clearBufferedAssistantText(messageId);
|
||||
clearBufferedAssistantText(messageId).pipe(
|
||||
Effect.andThen(Cache.invalidate(reasoningPartIndexByMessageId, messageId)),
|
||||
Effect.andThen(Cache.invalidate(reasoningStartedAtByMessageId, messageId)),
|
||||
);
|
||||
|
||||
const reasoningStartedAt = (messageId: MessageId, fallback: string) =>
|
||||
Cache.getOption(reasoningStartedAtByMessageId, messageId).pipe(
|
||||
Effect.map((started) => Option.getOrElse(started, () => fallback) || fallback),
|
||||
);
|
||||
|
||||
const flushBufferedAssistantMessage = (input: {
|
||||
event: ProviderRuntimeEvent;
|
||||
@@ -1286,14 +1410,17 @@ const make = Effect.gen(function* () {
|
||||
return false;
|
||||
}
|
||||
|
||||
const isReasoning = messageStreamRoleOf(input.messageId) === "reasoning";
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
type: isReasoning ? "thread.message.reasoning.delta" : "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: bufferedText,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
createdAt: input.createdAt,
|
||||
createdAt: isReasoning
|
||||
? yield* reasoningStartedAt(input.messageId, input.createdAt)
|
||||
: input.createdAt,
|
||||
});
|
||||
return true;
|
||||
});
|
||||
@@ -1352,21 +1479,27 @@ const make = Effect.gen(function* () {
|
||||
: "";
|
||||
const hasRenderableText = hasRenderableAssistantText(text);
|
||||
|
||||
const isReasoning = messageStreamRoleOf(input.messageId) === "reasoning";
|
||||
|
||||
if (hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.delta",
|
||||
type: isReasoning ? "thread.message.reasoning.delta" : "thread.message.assistant.delta",
|
||||
commandId: yield* providerCommandId(input.event, input.finalDeltaCommandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
delta: text,
|
||||
...(input.turnId ? { turnId: input.turnId } : {}),
|
||||
createdAt: input.createdAt,
|
||||
createdAt: isReasoning
|
||||
? yield* reasoningStartedAt(input.messageId, input.createdAt)
|
||||
: input.createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
if (input.hasProjectedMessage || hasRenderableText) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.assistant.complete",
|
||||
type: isReasoning
|
||||
? "thread.message.reasoning.complete"
|
||||
: "thread.message.assistant.complete",
|
||||
commandId: yield* providerCommandId(input.event, input.commandTag),
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
@@ -1377,7 +1510,7 @@ const make = Effect.gen(function* () {
|
||||
yield* clearAssistantMessageState(input.messageId);
|
||||
});
|
||||
|
||||
const finalizeActiveAssistantSegmentForTurn = (input: {
|
||||
const finalizeActiveSegmentForTurn = (input: {
|
||||
event: ProviderRuntimeEvent;
|
||||
threadId: ThreadId;
|
||||
turnId: TurnId;
|
||||
@@ -1386,16 +1519,29 @@ const make = Effect.gen(function* () {
|
||||
finalDeltaCommandTag: string;
|
||||
hasProjectedMessage: boolean;
|
||||
flushedMessageIds?: ReadonlySet<MessageId>;
|
||||
role?: MessageStreamRole;
|
||||
fallbackText?: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const role = input.role ?? "assistant";
|
||||
const activeMessageId = yield* getActiveAssistantMessageIdForTurn(
|
||||
input.threadId,
|
||||
input.turnId,
|
||||
role,
|
||||
);
|
||||
if (Option.isNone(activeMessageId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A block whose deltas already reached the projection must still be
|
||||
// completed, or it stays flagged as streaming forever.
|
||||
const alreadyProjected =
|
||||
input.hasProjectedMessage ||
|
||||
(input.flushedMessageIds?.has(activeMessageId.value) ?? false) ||
|
||||
(role === "reasoning"
|
||||
? (yield* getThreadMessageById(input.threadId, activeMessageId.value)) !== undefined
|
||||
: false);
|
||||
|
||||
yield* finalizeAssistantMessage({
|
||||
event: input.event,
|
||||
threadId: input.threadId,
|
||||
@@ -1404,18 +1550,21 @@ const make = Effect.gen(function* () {
|
||||
createdAt: input.createdAt,
|
||||
commandTag: input.commandTag,
|
||||
finalDeltaCommandTag: input.finalDeltaCommandTag,
|
||||
hasProjectedMessage:
|
||||
input.hasProjectedMessage ||
|
||||
(input.flushedMessageIds?.has(activeMessageId.value) ?? false),
|
||||
hasProjectedMessage: alreadyProjected,
|
||||
...(input.fallbackText !== undefined ? { fallbackText: input.fallbackText } : {}),
|
||||
});
|
||||
yield* forgetAssistantMessageId(input.threadId, input.turnId, activeMessageId.value);
|
||||
|
||||
const state = yield* getAssistantSegmentStateForTurn(input.threadId, input.turnId);
|
||||
// The segment index is deliberately preserved: reasoning blocks in one
|
||||
// turn can share a base key, so resetting it would reopen a closed block.
|
||||
const state = yield* getAssistantSegmentStateForTurn(input.threadId, input.turnId, role);
|
||||
if (Option.isSome(state)) {
|
||||
yield* setAssistantSegmentStateForTurn(input.threadId, input.turnId, {
|
||||
...state.value,
|
||||
activeMessageId: null,
|
||||
});
|
||||
yield* setAssistantSegmentStateForTurn(
|
||||
input.threadId,
|
||||
input.turnId,
|
||||
{ ...state.value, activeMessageId: null },
|
||||
role,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1596,7 +1745,12 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
if (event.type === "content.delta" && event.payload.streamKind !== "assistant_text") {
|
||||
if (
|
||||
event.type === "content.delta" &&
|
||||
event.payload.streamKind !== "assistant_text" &&
|
||||
event.payload.streamKind !== "reasoning_text" &&
|
||||
event.payload.streamKind !== "reasoning_summary_text"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1772,11 +1926,98 @@ const make = Effect.gen(function* () {
|
||||
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
|
||||
? event.payload.delta
|
||||
: undefined;
|
||||
const reasoningDelta =
|
||||
event.type === "content.delta" &&
|
||||
(event.payload.streamKind === "reasoning_text" ||
|
||||
event.payload.streamKind === "reasoning_summary_text")
|
||||
? {
|
||||
streamKind: event.payload.streamKind,
|
||||
delta: event.payload.delta,
|
||||
summaryIndex: event.payload.summaryIndex,
|
||||
contentIndex: event.payload.contentIndex,
|
||||
}
|
||||
: undefined;
|
||||
const proposedPlanDelta =
|
||||
event.type === "turn.proposed.delta" ? event.payload.delta : undefined;
|
||||
|
||||
const reasoningTurnId = toTurnId(event.turnId);
|
||||
// Every close path for a thinking block is keyed by turn. Without one the
|
||||
// block could never be completed, and a row stuck mid-thought is worse
|
||||
// than no row at all.
|
||||
if (reasoningDelta && reasoningDelta.delta.length > 0 && reasoningTurnId) {
|
||||
const turnId = reasoningTurnId;
|
||||
const reasoningMessageId = yield* getOrCreateReasoningMessageId({
|
||||
threadId: thread.id,
|
||||
event,
|
||||
baseKey: reasoningSegmentBaseKeyFromEvent(event, reasoningDelta.streamKind),
|
||||
createdAt: now,
|
||||
turnId,
|
||||
});
|
||||
yield* rememberAssistantMessageId(thread.id, turnId, reasoningMessageId);
|
||||
|
||||
if (
|
||||
Option.getOrElse(
|
||||
yield* Cache.getOption(reasoningStartedAtByMessageId, reasoningMessageId),
|
||||
() => "",
|
||||
) === ""
|
||||
) {
|
||||
yield* Cache.set(reasoningStartedAtByMessageId, reasoningMessageId, now);
|
||||
}
|
||||
|
||||
let delta = reasoningDelta.delta;
|
||||
const partIndex = reasoningDelta.summaryIndex ?? reasoningDelta.contentIndex;
|
||||
if (partIndex !== undefined) {
|
||||
const lastIndex = Option.getOrElse(
|
||||
yield* Cache.getOption(reasoningPartIndexByMessageId, reasoningMessageId),
|
||||
() => -1,
|
||||
);
|
||||
if (lastIndex >= 0 && lastIndex !== partIndex) {
|
||||
delta = `\n\n${delta}`;
|
||||
}
|
||||
yield* Cache.set(reasoningPartIndexByMessageId, reasoningMessageId, partIndex);
|
||||
}
|
||||
|
||||
// Reasoning is never delivered token by token, even when the project
|
||||
// asks for it: the block is collapsed by default, so a command, an
|
||||
// event-store write and a fan-out per token would buy nothing. Traces
|
||||
// are longer than the answers they precede.
|
||||
const streamingMode = yield* resolveResponseStreamingMode(thread.projectId);
|
||||
const reasoningMode = streamingMode === "token" ? "paragraph" : streamingMode;
|
||||
const spillChunk = yield* appendBufferedAssistantText(
|
||||
reasoningMessageId,
|
||||
delta,
|
||||
reasoningMode,
|
||||
yield* Clock.currentTimeMillis,
|
||||
);
|
||||
if (spillChunk.length > 0) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.reasoning.delta",
|
||||
commandId: yield* providerCommandId(event, "reasoning-delta-buffer-spill"),
|
||||
threadId: thread.id,
|
||||
messageId: reasoningMessageId,
|
||||
delta: spillChunk,
|
||||
turnId,
|
||||
createdAt: yield* reasoningStartedAt(reasoningMessageId, now),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (assistantDelta && assistantDelta.length > 0) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
// Visible text ends the thinking block that preceded it, so the next
|
||||
// block does not swallow this answer.
|
||||
if (turnId) {
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "reasoning-complete-on-assistant-text",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize-on-assistant-text",
|
||||
hasProjectedMessage: false,
|
||||
role: "reasoning",
|
||||
});
|
||||
}
|
||||
const assistantMessageId = yield* getOrCreateAssistantMessageId({
|
||||
threadId: thread.id,
|
||||
event,
|
||||
@@ -1845,7 +2086,18 @@ const make = Effect.gen(function* () {
|
||||
: "assistant-delta-flush-on-user-input-requested",
|
||||
})
|
||||
: new Set<MessageId>();
|
||||
yield* finalizeActiveAssistantSegmentForTurn({
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId: pauseForUserTurnId,
|
||||
createdAt: now,
|
||||
commandTag: "reasoning-complete-on-pause",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize-on-pause",
|
||||
hasProjectedMessage: false,
|
||||
role: "reasoning",
|
||||
flushedMessageIds,
|
||||
});
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId: pauseForUserTurnId,
|
||||
@@ -1868,6 +2120,99 @@ const make = Effect.gen(function* () {
|
||||
yield* appendBufferedProposedPlan(planId, proposedPlanDelta, now);
|
||||
}
|
||||
|
||||
// Tool work ends the thinking block that led to it. Without this a
|
||||
// provider that reuses one reasoning stream across a turn (Claude has no
|
||||
// per-block id) would append post-tool thinking to a block that already
|
||||
// sits above the tool row.
|
||||
if (event.type === "item.started" && isToolLifecycleItemType(event.payload.itemType)) {
|
||||
const toolTurnId = toTurnId(event.turnId);
|
||||
if (toolTurnId) {
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId: toolTurnId,
|
||||
createdAt: now,
|
||||
commandTag: "reasoning-complete-on-tool-start",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize-on-tool-start",
|
||||
hasProjectedMessage: false,
|
||||
role: "reasoning",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "item.completed" && event.payload.itemType === "reasoning") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
const activeReasoningMessageId = yield* getActiveAssistantMessageIdForTurn(
|
||||
thread.id,
|
||||
turnId,
|
||||
"reasoning",
|
||||
);
|
||||
// The item detail is a whole-block snapshot, so it may only stand in
|
||||
// for deltas that never arrived. Appending it to a streamed block
|
||||
// would print the reasoning twice.
|
||||
const existingReasoningMessage = Option.isSome(activeReasoningMessageId)
|
||||
? yield* getThreadMessageById(thread.id, activeReasoningMessageId.value)
|
||||
: undefined;
|
||||
const fallbackText =
|
||||
event.payload.detail !== undefined &&
|
||||
event.payload.detail.trim().length > 0 &&
|
||||
(existingReasoningMessage === undefined || existingReasoningMessage.text.length === 0)
|
||||
? event.payload.detail
|
||||
: undefined;
|
||||
|
||||
if (Option.isNone(activeReasoningMessageId)) {
|
||||
// Segment state outlives a closed block, so its presence means this
|
||||
// turn already streamed a trace and the snapshot would duplicate it.
|
||||
const turnAlreadyStreamedReasoning = Option.isSome(
|
||||
yield* getAssistantSegmentStateForTurn(thread.id, turnId, "reasoning"),
|
||||
);
|
||||
// A provider can report a whole block at once without streaming it.
|
||||
// The id is derived from the item rather than the segment counter so
|
||||
// a repeated completion rewrites that row instead of adding a copy.
|
||||
if (fallbackText !== undefined && !turnAlreadyStreamedReasoning) {
|
||||
const snapshotMessageId = assistantSegmentMessageId(
|
||||
`snapshot:${event.itemId ?? event.eventId}`,
|
||||
0,
|
||||
"reasoning",
|
||||
);
|
||||
const existingSnapshot = yield* getThreadMessageById(thread.id, snapshotMessageId);
|
||||
if (existingSnapshot === undefined) {
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.reasoning.delta",
|
||||
commandId: yield* providerCommandId(event, "reasoning-delta-snapshot"),
|
||||
threadId: thread.id,
|
||||
messageId: snapshotMessageId,
|
||||
delta: fallbackText,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
});
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.message.reasoning.complete",
|
||||
commandId: yield* providerCommandId(event, "reasoning-complete-snapshot"),
|
||||
threadId: thread.id,
|
||||
messageId: snapshotMessageId,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "reasoning-complete",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize",
|
||||
hasProjectedMessage: existingReasoningMessage !== undefined,
|
||||
role: "reasoning",
|
||||
...(fallbackText !== undefined ? { fallbackText } : {}),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const assistantCompletion =
|
||||
event.type === "item.completed" && event.payload.itemType === "assistant_message"
|
||||
? {
|
||||
@@ -1888,6 +2233,18 @@ const make = Effect.gen(function* () {
|
||||
|
||||
if (assistantCompletion) {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (turnId) {
|
||||
yield* finalizeActiveSegmentForTurn({
|
||||
event,
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
createdAt: now,
|
||||
commandTag: "reasoning-complete-on-assistant-completion",
|
||||
finalDeltaCommandTag: "reasoning-delta-finalize-on-assistant-completion",
|
||||
hasProjectedMessage: false,
|
||||
role: "reasoning",
|
||||
});
|
||||
}
|
||||
const activeAssistantMessageId = turnId
|
||||
? yield* getActiveAssistantMessageIdForTurn(thread.id, turnId)
|
||||
: Option.none<MessageId>();
|
||||
@@ -2020,6 +2377,7 @@ const make = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
yield* clearAssistantMessageIdsForTurn(thread.id, turnId);
|
||||
yield* clearAssistantSegmentStateForTurn(thread.id, turnId);
|
||||
yield* clearAssistantSegmentStateForTurn(thread.id, turnId, "reasoning");
|
||||
|
||||
yield* finalizeBufferedProposedPlan({
|
||||
event,
|
||||
|
||||
@@ -1912,7 +1912,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
return [unsettledEvent, sessionSetEvent];
|
||||
}
|
||||
|
||||
case "thread.message.assistant.delta": {
|
||||
case "thread.message.assistant.delta":
|
||||
case "thread.message.reasoning.delta": {
|
||||
if (isImportedAgentSessionMessageId(command.messageId)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -1935,7 +1936,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.messageId,
|
||||
role: "assistant",
|
||||
role: command.type === "thread.message.reasoning.delta" ? "reasoning" : "assistant",
|
||||
text: command.delta,
|
||||
turnId: command.turnId ?? null,
|
||||
streaming: true,
|
||||
@@ -1945,7 +1946,8 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.message.assistant.complete": {
|
||||
case "thread.message.assistant.complete":
|
||||
case "thread.message.reasoning.complete": {
|
||||
if (isImportedAgentSessionMessageId(command.messageId)) {
|
||||
return yield* new OrchestrationCommandInvariantError({
|
||||
commandType: command.type,
|
||||
@@ -1968,7 +1970,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.messageId,
|
||||
role: "assistant",
|
||||
role: command.type === "thread.message.reasoning.complete" ? "reasoning" : "assistant",
|
||||
text: "",
|
||||
turnId: command.turnId ?? null,
|
||||
streaming: false,
|
||||
|
||||
@@ -87,7 +87,10 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
|
||||
if (Option.isNone(snapshot)) {
|
||||
return yield* failEnvironmentNotFound("thread_not_found");
|
||||
}
|
||||
return projectThreadDetailSnapshot(snapshot.value);
|
||||
return projectThreadDetailSnapshot(
|
||||
snapshot.value,
|
||||
args.payload.reasoningMessages === "true",
|
||||
);
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
|
||||
@@ -496,7 +496,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
|
||||
// The honored flag is dropped from extraArgs so the CLI sees it once.
|
||||
assert.deepEqual(createInput?.options.extraArgs, { verbose: null });
|
||||
assert.deepEqual(createInput?.options.extraArgs, {
|
||||
verbose: null,
|
||||
"thinking-display": "summarized",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -553,7 +556,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const options = harness.getLastCreateQueryInput()?.options;
|
||||
assert.deepEqual(options?.settings, { autoCompactWindow: 300000 });
|
||||
assert.deepEqual(options?.settings, {
|
||||
showThinkingSummaries: true,
|
||||
autoCompactWindow: 300000,
|
||||
});
|
||||
assert.deepEqual(options?.supportedDialogKinds, ["resume_return"]);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
@@ -628,6 +634,61 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
alwaysThinkingEnabled: false,
|
||||
});
|
||||
assert.equal(createInput?.options.thinking, undefined);
|
||||
assert.equal(createInput?.options.extraArgs?.["thinking-display"], undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("requests Claude thinking summaries unless thinking is off", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("claudeAgent"),
|
||||
SYNTHETIC_CLAUDE_THINKING_MODEL,
|
||||
[{ id: "thinking", value: true }],
|
||||
),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
alwaysThinkingEnabled: true,
|
||||
showThinkingSummaries: true,
|
||||
});
|
||||
assert.deepEqual(createInput?.options.thinking, {
|
||||
type: "adaptive",
|
||||
display: "summarized",
|
||||
});
|
||||
assert.equal(createInput?.options.extraArgs?.["thinking-display"], "summarized");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("honors a launch-arg that omits Claude thinking display", () => {
|
||||
const harness = makeHarness({
|
||||
claudeConfig: { launchArgs: "--thinking-display omitted" },
|
||||
});
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.settings, undefined);
|
||||
assert.equal(createInput?.options.thinking, undefined);
|
||||
assert.equal(createInput?.options.extraArgs?.["thinking-display"], "omitted");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -650,7 +711,13 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.settings, undefined);
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
showThinkingSummaries: true,
|
||||
});
|
||||
assert.deepEqual(createInput?.options.thinking, {
|
||||
type: "adaptive",
|
||||
display: "summarized",
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -674,6 +741,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
showThinkingSummaries: true,
|
||||
fastMode: true,
|
||||
});
|
||||
}).pipe(
|
||||
@@ -698,7 +766,9 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.settings, undefined);
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
showThinkingSummaries: true,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -781,7 +851,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
const { options: customOptions, prompt: customPrompt } = yield* runCustomFlow;
|
||||
assert.equal(customOptions.model, SYNTHETIC_CLAUDE_COLLIDING_ALIAS);
|
||||
assert.equal(customOptions.effort, undefined);
|
||||
assert.equal(customOptions.settings, undefined);
|
||||
assert.deepEqual(customOptions.settings, { showThinkingSummaries: true });
|
||||
assert.deepEqual(customHarness.query.setModelCalls, [
|
||||
`${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded]`,
|
||||
SYNTHETIC_CLAUDE_COLLIDING_ALIAS,
|
||||
@@ -791,7 +861,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
const builtInOptions = yield* start(builtInHarness, SYNTHETIC_CLAUDE_CAPABLE_MODEL);
|
||||
assert.equal(builtInOptions.model, `${SYNTHETIC_CLAUDE_CAPABLE_MODEL}[expanded]`);
|
||||
assert.equal(builtInOptions.effort, "max");
|
||||
assert.deepEqual(builtInOptions.settings, { fastMode: true });
|
||||
assert.deepEqual(builtInOptions.settings, {
|
||||
showThinkingSummaries: true,
|
||||
fastMode: true,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1673,7 +1746,8 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
|
||||
const reasoningDelta = runtimeEvents.find(
|
||||
(event) => event.type === "content.delta" && event.payload.streamKind === "reasoning_text",
|
||||
(event) =>
|
||||
event.type === "content.delta" && event.payload.streamKind === "reasoning_summary_text",
|
||||
);
|
||||
assert.equal(reasoningDelta?.type, "content.delta");
|
||||
if (reasoningDelta?.type === "content.delta") {
|
||||
@@ -1727,6 +1801,87 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("backfills Claude thinking summaries from assistant snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.takeUntil(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.completed",
|
||||
).pipe(Stream.runCollect, Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
const thinkingSnapshot = {
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-thinking-snapshot",
|
||||
uuid: "assistant-thinking-snapshot",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-thinking",
|
||||
content: [
|
||||
{ type: "thinking", thinking: "Use Euclidean algorithm." },
|
||||
{ type: "text", text: "The gcd is 21." },
|
||||
],
|
||||
},
|
||||
} as unknown as SDKMessage;
|
||||
harness.query.emit(thinkingSnapshot);
|
||||
harness.query.emit(thinkingSnapshot);
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-thinking-snapshot",
|
||||
uuid: "assistant-thinking-snapshot-2",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-thinking-2",
|
||||
content: [{ type: "thinking", thinking: "Verify the result." }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-thinking-snapshot",
|
||||
uuid: "result-thinking-snapshot",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const reasoningDeltas = runtimeEvents.filter(
|
||||
(event) =>
|
||||
event.type === "content.delta" && event.payload.streamKind === "reasoning_summary_text",
|
||||
);
|
||||
assert.equal(reasoningDeltas.length, 2);
|
||||
const reasoningDelta = reasoningDeltas[0];
|
||||
assert.equal(reasoningDelta?.type, "content.delta");
|
||||
if (reasoningDelta?.type === "content.delta") {
|
||||
assert.equal(reasoningDelta.payload.delta, "Use Euclidean algorithm.");
|
||||
assert.equal(String(reasoningDelta.turnId), String(turn.turnId));
|
||||
}
|
||||
assert.deepEqual(
|
||||
runtimeEvents.flatMap((event) =>
|
||||
event.type === "content.delta" ? [event.payload.delta] : [],
|
||||
),
|
||||
["Use Euclidean algorithm.", "The gcd is 21.", "Verify the result."],
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("classifies only streamed Read image inputs as image views", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -225,7 +225,10 @@ const remapClaudeForkTurnBoundaries = (
|
||||
};
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("claudeAgent");
|
||||
type ClaudeTextStreamKind = Extract<RuntimeContentStreamKind, "assistant_text" | "reasoning_text">;
|
||||
type ClaudeTextStreamKind = Extract<
|
||||
RuntimeContentStreamKind,
|
||||
"assistant_text" | "reasoning_text" | "reasoning_summary_text"
|
||||
>;
|
||||
type ClaudeToolResultStreamKind = Extract<
|
||||
RuntimeContentStreamKind,
|
||||
"command_output" | "file_change_output"
|
||||
@@ -275,6 +278,8 @@ interface ClaudeTurnState {
|
||||
authenticationFailureMessage: string | undefined;
|
||||
rejectedRateLimitTypes: Set<string>;
|
||||
latestAssistantRateLimited: boolean;
|
||||
emittedThinkingText: boolean;
|
||||
readonly thinkingSnapshotIds: Set<string>;
|
||||
}
|
||||
|
||||
interface AssistantTextBlockState {
|
||||
@@ -1718,7 +1723,18 @@ function resultOutcome(
|
||||
}
|
||||
|
||||
function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {
|
||||
return deltaType.includes("thinking") ? "reasoning_text" : "assistant_text";
|
||||
// Claude never returns the raw chain of thought. A thinking delta is the
|
||||
// API-side summary (or a progress-update sentence) when display is
|
||||
// summarized; map it onto the summary stream so it shares the Codex/Grok
|
||||
// reasoning-summary path rather than looking like a raw trace we do not have.
|
||||
return deltaType.includes("thinking") ? "reasoning_summary_text" : "assistant_text";
|
||||
}
|
||||
|
||||
function shouldRequestClaudeThinkingSummaries(input: {
|
||||
readonly thinking: boolean | undefined;
|
||||
readonly thinkingDisplay: string | null | undefined;
|
||||
}): boolean {
|
||||
return input.thinking !== false && input.thinkingDisplay !== "omitted";
|
||||
}
|
||||
|
||||
function nativeProviderRefs(
|
||||
@@ -1735,7 +1751,11 @@ function nativeProviderRefs(
|
||||
return {};
|
||||
}
|
||||
|
||||
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
|
||||
function extractAssistantContentBlocks(
|
||||
message: SDKMessage,
|
||||
blockType: "text" | "thinking",
|
||||
field: "text" | "thinking",
|
||||
): Array<string> {
|
||||
if (message.type !== "assistant") {
|
||||
return [];
|
||||
}
|
||||
@@ -1750,19 +1770,24 @@ function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
|
||||
if (!block || typeof block !== "object") {
|
||||
continue;
|
||||
}
|
||||
const candidate = block as { type?: unknown; text?: unknown };
|
||||
if (
|
||||
candidate.type === "text" &&
|
||||
typeof candidate.text === "string" &&
|
||||
candidate.text.length > 0
|
||||
) {
|
||||
fragments.push(candidate.text);
|
||||
const candidate = block as { type?: unknown; text?: unknown; thinking?: unknown };
|
||||
const value = field === "thinking" ? candidate.thinking : candidate.text;
|
||||
if (candidate.type === blockType && typeof value === "string" && value.length > 0) {
|
||||
fragments.push(value);
|
||||
}
|
||||
}
|
||||
|
||||
return fragments;
|
||||
}
|
||||
|
||||
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
|
||||
return extractAssistantContentBlocks(message, "text", "text");
|
||||
}
|
||||
|
||||
function extractAssistantThinkingBlocks(message: SDKMessage): Array<string> {
|
||||
return extractAssistantContentBlocks(message, "thinking", "thinking");
|
||||
}
|
||||
|
||||
function extractContentBlockText(block: unknown): string {
|
||||
if (!block || typeof block !== "object") {
|
||||
return "";
|
||||
@@ -2358,6 +2383,70 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
});
|
||||
|
||||
const emitReasoningSummaryDelta = Effect.fn("emitReasoningSummaryDelta")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
readonly delta: string;
|
||||
readonly contentIndex?: number;
|
||||
readonly rawMethod: string;
|
||||
readonly rawPayload: SDKMessage;
|
||||
},
|
||||
) {
|
||||
const turnState = context.turnState;
|
||||
if (!turnState || input.delta.length === 0) {
|
||||
return;
|
||||
}
|
||||
turnState.emittedThinkingText = true;
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "content.delta",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
streamKind: "reasoning_summary_text",
|
||||
delta: input.delta,
|
||||
...(input.contentIndex !== undefined ? { contentIndex: input.contentIndex } : {}),
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: input.rawMethod,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const backfillThinkingFromSnapshot = Effect.fn("backfillThinkingFromSnapshot")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
) {
|
||||
const turnState = context.turnState;
|
||||
if (!turnState || message.type !== "assistant") {
|
||||
return;
|
||||
}
|
||||
const snapshotId = message.uuid;
|
||||
const alreadyEmitted =
|
||||
turnState.emittedThinkingText || turnState.thinkingSnapshotIds.has(snapshotId);
|
||||
turnState.thinkingSnapshotIds.add(snapshotId);
|
||||
turnState.emittedThinkingText = false;
|
||||
if (alreadyEmitted) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [index, delta] of extractAssistantThinkingBlocks(message).entries()) {
|
||||
yield* emitReasoningSummaryDelta(context, {
|
||||
delta,
|
||||
contentIndex: index,
|
||||
rawMethod: "claude/assistant/thinking",
|
||||
rawPayload: message,
|
||||
});
|
||||
}
|
||||
turnState.emittedThinkingText = false;
|
||||
});
|
||||
|
||||
const ensureThreadId = Effect.fn("ensureThreadId")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
@@ -2799,6 +2888,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
}
|
||||
}
|
||||
|
||||
if (event.type === "message_start" && context.turnState && !streamParentToolUseId) {
|
||||
context.turnState.emittedThinkingText = false;
|
||||
}
|
||||
|
||||
if (event.type === "message_delta") {
|
||||
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
|
||||
return;
|
||||
@@ -2831,18 +2924,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
return;
|
||||
}
|
||||
const streamKind = streamKindFromDeltaType(event.delta.type);
|
||||
const assistantBlockEntry =
|
||||
event.delta.type === "text_delta"
|
||||
? yield* ensureAssistantTextBlock(context, event.index)
|
||||
: context.turnState.assistantTextBlocks.get(event.index)
|
||||
? {
|
||||
blockIndex: event.index,
|
||||
block: context.turnState.assistantTextBlocks.get(
|
||||
event.index,
|
||||
) as AssistantTextBlockState,
|
||||
}
|
||||
: undefined;
|
||||
if (assistantBlockEntry?.block && event.delta.type === "text_delta") {
|
||||
if (streamKind === "reasoning_summary_text") {
|
||||
yield* emitReasoningSummaryDelta(context, {
|
||||
delta: deltaText,
|
||||
contentIndex: event.index,
|
||||
rawMethod: "claude/stream_event/content_block_delta",
|
||||
rawPayload: message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const assistantBlockEntry = yield* ensureAssistantTextBlock(context, event.index);
|
||||
if (assistantBlockEntry?.block) {
|
||||
assistantBlockEntry.block.emittedTextDelta = true;
|
||||
}
|
||||
const stamp = yield* makeEventStamp();
|
||||
@@ -3297,6 +3389,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
authenticationFailureMessage: undefined,
|
||||
rejectedRateLimitTypes: new Set(),
|
||||
latestAssistantRateLimited: false,
|
||||
emittedThinkingText: false,
|
||||
thinkingSnapshotIds: new Set(),
|
||||
};
|
||||
context.session = {
|
||||
...context.session,
|
||||
@@ -3378,6 +3472,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
context.turnState.latestAssistantUsage = message.message.usage;
|
||||
context.turnState.compactedSinceLatestAssistantUsage = false;
|
||||
}
|
||||
yield* backfillThinkingFromSnapshot(context, message);
|
||||
yield* backfillAssistantTextBlocksFromSnapshot(context, message);
|
||||
}
|
||||
|
||||
@@ -4770,6 +4865,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const thinking = thinkingSupported
|
||||
? getModelSelectionBooleanOptionValue(modelSelection, "thinking")
|
||||
: undefined;
|
||||
const thinkingDisplayArg = extraArgs["thinking-display"];
|
||||
const requestThinkingSummaries = shouldRequestClaudeThinkingSummaries({
|
||||
thinking,
|
||||
thinkingDisplay: typeof thinkingDisplayArg === "string" ? thinkingDisplayArg : undefined,
|
||||
});
|
||||
const ultracode = isClaudeCatalogUltracodeEffort(effort);
|
||||
const effectiveEffort = getEffectiveClaudeAgentEffort(
|
||||
modelCatalog,
|
||||
@@ -4791,12 +4891,16 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
: runtimeModeToPermission[input.runtimeMode]);
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(requestThinkingSummaries ? { showThinkingSummaries: true } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(ultracode ? { ultracode: true } : {}),
|
||||
...(claudeSettings.autoCompactWindow
|
||||
? { autoCompactWindow: Number(claudeSettings.autoCompactWindow) }
|
||||
: {}),
|
||||
};
|
||||
if (requestThinkingSummaries && extraArgs["thinking-display"] === undefined) {
|
||||
extraArgs["thinking-display"] = "summarized";
|
||||
}
|
||||
const mcpSession = McpProviderSession.readMcpProviderSession(input.threadId);
|
||||
// The attachments dir grant lets the agent Read/copy pasted images at
|
||||
// the paths ProviderService injects into the turn text, without an
|
||||
@@ -4824,6 +4928,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
effort: effectiveEffort as unknown as NonNullable<ClaudeQueryOptions["effort"]>,
|
||||
}
|
||||
: {}),
|
||||
...(extraArgs["thinking-display"] === "summarized"
|
||||
? {
|
||||
thinking: {
|
||||
type: "adaptive" as const,
|
||||
display: "summarized" as const,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(permissionMode === "bypassPermissions"
|
||||
? { allowDangerouslySkipPermissions: true }
|
||||
@@ -5104,6 +5216,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
authenticationFailureMessage: undefined,
|
||||
rejectedRateLimitTypes: new Set(),
|
||||
latestAssistantRateLimited: false,
|
||||
emittedThinkingText: false,
|
||||
thinkingSnapshotIds: new Set(),
|
||||
};
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
|
||||
@@ -877,6 +877,27 @@ export function makeCursorAdapter(
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ThoughtDelta":
|
||||
// Thoughts are narration, not the reply: they stay out of
|
||||
// `assistantReply` so a resumed turn replays only answers.
|
||||
yield* logNative(
|
||||
ctx.threadId,
|
||||
"session/update",
|
||||
event.rawPayload,
|
||||
"acp.jsonrpc",
|
||||
);
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp: yield* makeEventStamp(),
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: ctx.activeTurnId,
|
||||
streamKind: "reasoning_text",
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
ctx.assistantReply.push(event.text);
|
||||
yield* logNative(
|
||||
|
||||
@@ -467,13 +467,15 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
| "AssistantItemCompleted"
|
||||
| "PlanUpdated"
|
||||
| "ToolCallUpdated"
|
||||
| "ContentDelta";
|
||||
| "ContentDelta"
|
||||
| "ThoughtDelta";
|
||||
}
|
||||
>,
|
||||
) {
|
||||
if (
|
||||
ctx.livenessTurnId !== turnId ||
|
||||
(event._tag === "ContentDelta" && event.text.length === 0)
|
||||
((event._tag === "ContentDelta" || event._tag === "ThoughtDelta") &&
|
||||
event.text.length === 0)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -1367,7 +1369,8 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
event._tag === "AssistantItemCompleted" ||
|
||||
event._tag === "PlanUpdated" ||
|
||||
event._tag === "ToolCallUpdated" ||
|
||||
event._tag === "ContentDelta"
|
||||
event._tag === "ContentDelta" ||
|
||||
event._tag === "ThoughtDelta"
|
||||
) {
|
||||
yield* recordTurnActivity(ctx, notificationTurnId, event);
|
||||
}
|
||||
@@ -1443,6 +1446,19 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "ThoughtDelta":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
stamp,
|
||||
provider: PROVIDER,
|
||||
threadId: ctx.threadId,
|
||||
turnId: notificationTurnId,
|
||||
streamKind: "reasoning_text",
|
||||
text: event.text,
|
||||
rawPayload: event.rawPayload,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
case "ContentDelta":
|
||||
yield* offerRuntimeEvent(
|
||||
makeAcpContentDeltaEvent({
|
||||
|
||||
@@ -8525,6 +8525,124 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
|
||||
for (const reasoningMessages of [undefined, true] as const) {
|
||||
it.effect(`preserves reasoning wire compatibility with opt-in ${reasoningMessages}`, () =>
|
||||
Effect.gen(function* () {
|
||||
const message = {
|
||||
id: MessageId.make("thinking-compatibility"),
|
||||
role: "reasoning" as const,
|
||||
text: "Checking the available evidence.",
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:01.000Z",
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
};
|
||||
const thread = { ...makeDefaultOrchestrationReadModel().threads[0]!, messages: [message] };
|
||||
const event = {
|
||||
sequence: 2,
|
||||
eventId: EventId.make("thinking-compatibility-event"),
|
||||
aggregateKind: "thread" as const,
|
||||
aggregateId: defaultThreadId,
|
||||
occurredAt: message.createdAt,
|
||||
commandId: null,
|
||||
causationEventId: null,
|
||||
correlationId: null,
|
||||
metadata: {},
|
||||
type: "thread.message-sent" as const,
|
||||
payload: {
|
||||
messageId: message.id,
|
||||
threadId: defaultThreadId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
turnId: message.turnId,
|
||||
streaming: message.streaming,
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.updatedAt,
|
||||
},
|
||||
} satisfies OrchestrationEvent;
|
||||
const answer = {
|
||||
...event,
|
||||
sequence: 3,
|
||||
eventId: EventId.make("thinking-answer-event"),
|
||||
payload: {
|
||||
...event.payload,
|
||||
messageId: MessageId.make("thinking-answer"),
|
||||
role: "assistant" as const,
|
||||
text: "Here is the answer.",
|
||||
},
|
||||
};
|
||||
const liveEvents = yield* PubSub.unbounded<OrchestrationEvent>();
|
||||
yield* buildAppUnderTest({
|
||||
layers: {
|
||||
orchestrationEngine: {
|
||||
streamDomainEvents: Stream.fromPubSub(liveEvents),
|
||||
latestSequence: Effect.succeed(3),
|
||||
getThreadReplayStats: () =>
|
||||
Effect.succeed({ eventCount: 2, payloadBytes: 200, hasCreateEvent: false }),
|
||||
readThreadEvents: () => Stream.make(event, answer),
|
||||
},
|
||||
projectionSnapshotQuery: {
|
||||
getThreadDetailSnapshot: () =>
|
||||
Effect.gen(function* () {
|
||||
yield* PubSub.publishAll(liveEvents, [event, answer]);
|
||||
return Option.some({
|
||||
snapshotSequence: 1,
|
||||
thread,
|
||||
page: {
|
||||
beforeCursor: null,
|
||||
hasMore: false,
|
||||
snapshotSequence: 1,
|
||||
threadSequence: 2,
|
||||
},
|
||||
});
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
const role = reasoningMessages ? "reasoning" : "system";
|
||||
const response = yield* fetchEffect(
|
||||
yield* getHttpServerUrl(
|
||||
`/api/orchestration/threads/${defaultThreadId}?turnLimit=1${reasoningMessages ? "&reasoningMessages=true" : ""}`,
|
||||
),
|
||||
{ headers: { cookie: yield* getAuthenticatedSessionCookieHeader() } },
|
||||
);
|
||||
const httpSnapshot = yield* responseJsonEffect<OrchestrationThreadDetailSnapshot>(response);
|
||||
assert.equal(response.status, 200);
|
||||
assert.deepEqual(httpSnapshot.thread.messages, [{ ...message, role }]);
|
||||
assert.equal(httpSnapshot.page?.threadSequence, 2);
|
||||
const wsUrl = yield* getWsServerUrl("/ws");
|
||||
for (const afterSequence of [undefined, 1]) {
|
||||
const items = yield* Effect.scoped(
|
||||
withWsRpcClient(wsUrl, (client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.subscribeThread]({
|
||||
threadId: defaultThreadId,
|
||||
requestCompletionMarker: true,
|
||||
...(reasoningMessages ? { reasoningMessages } : {}),
|
||||
...(afterSequence !== undefined ? { afterSequence } : {}),
|
||||
}).pipe(
|
||||
Stream.takeUntil((item) => item.kind === "synchronized"),
|
||||
Stream.runCollect,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (afterSequence === undefined) {
|
||||
const first = items[0];
|
||||
assertTrue(first?.kind === "snapshot");
|
||||
assert.deepEqual(first.snapshot.thread.messages, [{ ...message, role }]);
|
||||
assert.equal(first.snapshot.page?.threadSequence, 2);
|
||||
}
|
||||
const events = items.filter((item) => item.kind === "event");
|
||||
assert.equal(events.length, 2);
|
||||
assert.deepEqual(events[0]?.event, { ...event, payload: { ...event.payload, role } });
|
||||
assert.deepEqual(events[1]?.event, answer);
|
||||
assert.deepEqual(items.at(-1), { kind: "synchronized" });
|
||||
}
|
||||
assert.equal(message.role, "reasoning");
|
||||
assert.equal(event.payload.role, "reasoning");
|
||||
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("marks a socket thread snapshot as synchronized when requested", () =>
|
||||
Effect.gen(function* () {
|
||||
const thread = makeDefaultOrchestrationReadModel().threads[0]!;
|
||||
|
||||
@@ -45,4 +45,14 @@ describe("thread title context", () => {
|
||||
}
|
||||
expect(formatThreadTitleContext([])).toEqual({ message: "", attachments: [] });
|
||||
});
|
||||
|
||||
it("omits reasoning traces from generated titles", () => {
|
||||
expect(
|
||||
formatThreadTitleContext([
|
||||
{ role: "user", text: "Fix pairing" },
|
||||
{ role: "reasoning", text: "Consider token expiry, then the QR payload." },
|
||||
{ role: "assistant", text: "The QR token expired." },
|
||||
]).message,
|
||||
).toBe("USER:\nFix pairing\n\nASSISTANT:\nThe QR token expired.");
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import type { ChatAttachment } from "@t3tools/contracts";
|
||||
import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations";
|
||||
|
||||
export type ThreadTitleMessage = {
|
||||
readonly role: "user" | "assistant" | "system";
|
||||
readonly role: "user" | "assistant" | "system" | "reasoning";
|
||||
readonly text: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
};
|
||||
@@ -25,7 +25,13 @@ export function limitTitleMessage(text: string, budget: number): string {
|
||||
/** Reserve space for user intent before adding assistant findings, in conversation order. */
|
||||
export function formatThreadTitleContext(messages: ReadonlyArray<ThreadTitleMessage>) {
|
||||
const sections = messages.flatMap((message, index) => {
|
||||
if (message.role === "system" || (!message.text.trim() && !message.attachments?.length))
|
||||
// Thinking traces are working notes, not what the thread is about, and they
|
||||
// dwarf the answer they precede. Titling on them would be worse and costlier.
|
||||
if (
|
||||
message.role === "system" ||
|
||||
message.role === "reasoning" ||
|
||||
(!message.text.trim() && !message.attachments?.length)
|
||||
)
|
||||
return [];
|
||||
return [{ index, message, prefix: `${message.role.toUpperCase()}:\n` }];
|
||||
});
|
||||
|
||||
@@ -1807,6 +1807,7 @@ const makeWsRpcLayer = (
|
||||
}),
|
||||
threadResumeCompletionMarker: true,
|
||||
threadSnapshotPagination: true,
|
||||
reasoningMessages: true,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -2137,7 +2138,7 @@ const makeWsRpcLayer = (
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event,
|
||||
event: projectActivityEvent(event, input.reasoningMessages === true),
|
||||
})),
|
||||
);
|
||||
|
||||
@@ -2207,7 +2208,7 @@ const makeWsRpcLayer = (
|
||||
Stream.filter(isThisThreadDetailEvent),
|
||||
Stream.map((event) => ({
|
||||
kind: "event" as const,
|
||||
event: projectActivityEvent(event),
|
||||
event: projectActivityEvent(event, input.reasoningMessages === true),
|
||||
})),
|
||||
Stream.mapError(
|
||||
(cause) =>
|
||||
@@ -2278,7 +2279,10 @@ const makeWsRpcLayer = (
|
||||
return Stream.concat(
|
||||
Stream.make({
|
||||
kind: "snapshot" as const,
|
||||
snapshot: projectThreadDetailSnapshot(snapshot.value),
|
||||
snapshot: projectThreadDetailSnapshot(
|
||||
snapshot.value,
|
||||
input.reasoningMessages === true,
|
||||
),
|
||||
}),
|
||||
afterSnapshot,
|
||||
);
|
||||
|
||||
@@ -1907,6 +1907,118 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(rows.map((row) => row.id)).toEqual(["turn-fold:turn-1", "assistant-final-entry"]);
|
||||
});
|
||||
|
||||
const reasoningEntry = (id: string, at: string, turnId: string | null) => ({
|
||||
id,
|
||||
kind: "message" as const,
|
||||
createdAt: at,
|
||||
message: {
|
||||
id: id as never,
|
||||
role: "reasoning" as const,
|
||||
text: "weighing it up",
|
||||
turnId: turnId as never,
|
||||
createdAt: at,
|
||||
updatedAt: at,
|
||||
streaming: false,
|
||||
},
|
||||
});
|
||||
|
||||
const answerEntry = (id: string, at: string, turnId: string) => ({
|
||||
id,
|
||||
kind: "message" as const,
|
||||
createdAt: at,
|
||||
message: {
|
||||
id: id as never,
|
||||
role: "assistant" as const,
|
||||
text: "the answer",
|
||||
turnId: turnId as never,
|
||||
createdAt: at,
|
||||
updatedAt: at,
|
||||
streaming: false,
|
||||
},
|
||||
});
|
||||
|
||||
const toolEntry = (id: string, at: string, turnId: string) => ({
|
||||
id,
|
||||
kind: "work" as const,
|
||||
createdAt: at,
|
||||
entry: {
|
||||
id,
|
||||
createdAt: at,
|
||||
turnId: turnId as never,
|
||||
label: "Ran a command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
});
|
||||
|
||||
it("keeps a thought-only turn out of the work fold", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
reasoningEntry("reasoning-entry", "2026-01-01T00:00:01Z", "turn-1"),
|
||||
answerEntry("assistant-entry", "2026-01-01T00:00:02Z", "turn-1"),
|
||||
],
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaries: [],
|
||||
supportsConversationRollback: false,
|
||||
});
|
||||
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
|
||||
expect(rows.map((row) => row.id)).toContain("reasoning-entry");
|
||||
});
|
||||
|
||||
it("folds a thinking block away with the tool work beside it", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
reasoningEntry("reasoning-entry", "2026-01-01T00:00:01Z", "turn-1"),
|
||||
toolEntry("tool-entry", "2026-01-01T00:00:02Z", "turn-1"),
|
||||
answerEntry("assistant-entry", "2026-01-01T00:00:03Z", "turn-1"),
|
||||
],
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaries: [],
|
||||
supportsConversationRollback: false,
|
||||
});
|
||||
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(true);
|
||||
expect(rows.map((row) => row.id)).not.toContain("reasoning-entry");
|
||||
});
|
||||
|
||||
it("still folds a lone trailing tool call when a thought follows the answer", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
toolEntry("tool-before", "2026-01-01T00:00:01Z", "turn-1"),
|
||||
answerEntry("assistant-entry", "2026-01-01T00:00:02Z", "turn-1"),
|
||||
reasoningEntry("reasoning-after", "2026-01-01T00:00:03Z", "turn-1"),
|
||||
toolEntry("tool-after", "2026-01-01T00:00:04Z", "turn-1"),
|
||||
],
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaries: [],
|
||||
supportsConversationRollback: false,
|
||||
});
|
||||
|
||||
const ids = rows.map((row) => row.id);
|
||||
expect(ids).not.toContain("tool-after");
|
||||
expect(ids).not.toContain("reasoning-after");
|
||||
});
|
||||
|
||||
it("does not let a stranded streaming thought hold a settled turn open", () => {
|
||||
const stranded = reasoningEntry("reasoning-stranded", "2026-01-01T00:00:01Z", "turn-1");
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{ ...stranded, message: { ...stranded.message, streaming: true } },
|
||||
toolEntry("tool-entry", "2026-01-01T00:00:02Z", "turn-1"),
|
||||
answerEntry("assistant-entry", "2026-01-01T00:00:03Z", "turn-1"),
|
||||
],
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaries: [],
|
||||
supportsConversationRollback: false,
|
||||
});
|
||||
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(true);
|
||||
});
|
||||
|
||||
it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
|
||||
// A steer ends the previous turn early: its only message completes the
|
||||
// instant it is created, and trailing work entries land after it. The
|
||||
|
||||
@@ -299,7 +299,7 @@ function maxIsoTimestamp(a: string | null, b: string | null): string | null {
|
||||
|
||||
export interface TimelineDurationMessage {
|
||||
id: string;
|
||||
role: "user" | "assistant" | "system";
|
||||
role: ChatMessage["role"];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
streaming: boolean;
|
||||
@@ -524,7 +524,7 @@ interface TurnFold {
|
||||
* user sends a message, the previous turn is still the "active" one until the
|
||||
* server creates the new turn, and folding must not flicker through that window.
|
||||
*/
|
||||
function deriveUnsettledTurnId(
|
||||
export function deriveUnsettledTurnId(
|
||||
latestTurn: TimelineLatestTurn | null,
|
||||
runningTurnId: TurnId | null,
|
||||
): TurnId | null {
|
||||
@@ -546,7 +546,9 @@ function lastUserMessageIndex(timelineEntries: ReadonlyArray<TimelineEntry>): nu
|
||||
|
||||
function timelineEntryTurnId(entry: TimelineEntry): TurnId | null {
|
||||
if (entry.kind === "message") {
|
||||
return entry.message.role === "assistant" ? (entry.message.turnId ?? null) : null;
|
||||
return entry.message.role === "assistant" || entry.message.role === "reasoning"
|
||||
? (entry.message.turnId ?? null)
|
||||
: null;
|
||||
}
|
||||
if (entry.kind === "proposed-plan") {
|
||||
return entry.proposedPlan.turnId;
|
||||
@@ -624,8 +626,13 @@ function deriveTurnFolds(input: {
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
// Thinking is work, so it folds with the rest of it. A provider that
|
||||
// interleaves a block with every tool call would otherwise leave dozens of
|
||||
// "Thought" rows standing beside the "Worked for ..." summary.
|
||||
// Nothing folds while the turn is live, which is when traces are watched.
|
||||
const turnId =
|
||||
entry.kind === "message" && entry.message.role === "assistant"
|
||||
entry.kind === "message" &&
|
||||
(entry.message.role === "assistant" || entry.message.role === "reasoning")
|
||||
? (entry.message.turnId ?? null)
|
||||
: entry.kind === "work"
|
||||
? (entry.entry.turnId ?? null)
|
||||
@@ -652,7 +659,10 @@ function deriveTurnFolds(input: {
|
||||
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
|
||||
group.terminalEntry = entry;
|
||||
}
|
||||
if (entry.message.streaming) {
|
||||
// A live turn is already excluded above, so only an answer still being
|
||||
// written may hold a fold open. A thinking block stranded by a crashed
|
||||
// provider keeps its streaming flag forever and must not.
|
||||
if (entry.message.streaming && entry.message.role !== "reasoning") {
|
||||
group.hasStreamingMessage = true;
|
||||
}
|
||||
}
|
||||
@@ -670,6 +680,15 @@ function deriveTurnFolds(input: {
|
||||
const terminalEntryIndex = group.terminalEntry
|
||||
? group.entries.findIndex((entry) => entry.id === group.terminalEntry?.id)
|
||||
: group.entries.length;
|
||||
// Thinking blocks do not count toward "one trailing activity": a block can
|
||||
// follow the answer, and it must not stop that lone tool call from folding
|
||||
// the way it did before traces existed. Loop-invariant, so it is counted
|
||||
// once: a long turn re-derives these rows on every work-log change.
|
||||
const trailingEntryCount = group.entries.filter(
|
||||
(candidate, candidateIndex) =>
|
||||
candidateIndex > terminalEntryIndex &&
|
||||
!(candidate.kind === "message" && candidate.message.role === "reasoning"),
|
||||
).length;
|
||||
for (const [index, entry] of group.entries.entries()) {
|
||||
if (entry.id === group.terminalEntry?.id) {
|
||||
continue;
|
||||
@@ -677,10 +696,18 @@ function deriveTurnFolds(input: {
|
||||
const isCompaction =
|
||||
entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction";
|
||||
const isSingleTrailingActivity =
|
||||
group.entries.length === terminalEntryIndex + 2 &&
|
||||
trailingEntryCount === 1 &&
|
||||
entry.kind === "work" &&
|
||||
!workEntryDisplayIndicatesToolFailure(entry.entry);
|
||||
if (!isCompaction && index > terminalEntryIndex && !isSingleTrailingActivity) {
|
||||
// A thinking block after the answer folds with its turn rather than
|
||||
// trailing under it, which is what mobile already does.
|
||||
const isReasoning = entry.kind === "message" && entry.message.role === "reasoning";
|
||||
if (
|
||||
!isCompaction &&
|
||||
!isReasoning &&
|
||||
index > terminalEntryIndex &&
|
||||
!isSingleTrailingActivity
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
// User input and subagent batches stay visible after their turn settles.
|
||||
@@ -696,13 +723,16 @@ function deriveTurnFolds(input: {
|
||||
continue;
|
||||
}
|
||||
// A lone compaction row stays visible on its own; it only folds away as
|
||||
// part of a turn that already folds other work.
|
||||
const hidesNonCompactionWork = group.entries.some(
|
||||
// part of a turn that already folds other work. Thinking is the same: a
|
||||
// question answered by thought alone keeps its "Thought" row
|
||||
// rather than collapsing behind a "Worked for ..." that hides nothing else.
|
||||
const hidesFoldableWork = group.entries.some(
|
||||
(entry) =>
|
||||
hiddenEntryIds.has(entry.id) &&
|
||||
!(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction"),
|
||||
!(entry.kind === "work" && entry.entry.sourceActivityKind === "context-compaction") &&
|
||||
!(entry.kind === "message" && entry.message.role === "reasoning"),
|
||||
);
|
||||
if (!hidesNonCompactionWork) {
|
||||
if (!hidesFoldableWork) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -778,7 +808,15 @@ function attachTrailingToolGroupsToAssistant(
|
||||
let hasTrailingToolGroup = false;
|
||||
for (let index = messageIndex + 1; index < rows.length; index += 1) {
|
||||
const candidate = rows[index];
|
||||
if (!candidate || candidate.kind === "message") {
|
||||
if (!candidate) {
|
||||
break;
|
||||
}
|
||||
// A thinking block can follow the answer (the next one starts before its
|
||||
// tool call); it is not another message in the conversation.
|
||||
if (candidate.kind === "message" && candidate.message.role === "reasoning") {
|
||||
continue;
|
||||
}
|
||||
if (candidate.kind === "message") {
|
||||
break;
|
||||
}
|
||||
if (candidate.kind === "work-toggle" && candidate.turnId === turnId) {
|
||||
@@ -1326,6 +1364,16 @@ export function deriveMessagesTimelineRows(input: {
|
||||
);
|
||||
}
|
||||
}
|
||||
// A live thinking block is the real version of the placeholder below, so it
|
||||
// suppresses it rather than sitting under a second "Thinking" row.
|
||||
const hasStreamingReasoningRow = nextRows.some(
|
||||
(row) =>
|
||||
row.kind === "message" &&
|
||||
row.message.role === "reasoning" &&
|
||||
row.message.streaming &&
|
||||
row.message.turnId !== null &&
|
||||
row.message.turnId === unsettledTurnId,
|
||||
);
|
||||
|
||||
// A running setup owns the working slot above its card and shows no
|
||||
// activity row of its own; every other state gets the usual tail.
|
||||
@@ -1333,7 +1381,12 @@ export function deriveMessagesTimelineRows(input: {
|
||||
if (input.isWorking && !hasWorkingRow && activeTurnHeaderIndex === input.timelineEntries.length) {
|
||||
appendWorkingRow();
|
||||
}
|
||||
if (input.isWorking && !setupRunning && (!hasActivityRow || latestToolFailed)) {
|
||||
if (
|
||||
input.isWorking &&
|
||||
!setupRunning &&
|
||||
!hasStreamingReasoningRow &&
|
||||
(!hasActivityRow || latestToolFailed)
|
||||
) {
|
||||
nextRows.push({
|
||||
kind: "thinking",
|
||||
id: LIVE_ACTIVITY_ROW_ID,
|
||||
|
||||
@@ -167,6 +167,7 @@ import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssis
|
||||
import {
|
||||
computeStableMessagesTimelineRows,
|
||||
deriveMessagesTimelineRowsWithState,
|
||||
deriveUnsettledTurnId,
|
||||
type MessagesTimelineRowsProjection,
|
||||
liveWorkEntryLabel,
|
||||
resolveAssistantMessageCopyState,
|
||||
@@ -280,6 +281,8 @@ interface TimelineRowSharedState {
|
||||
onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
|
||||
onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void;
|
||||
onToggleSpawnRow: (entryId: string, expanded: boolean) => void;
|
||||
onToggleReasoning: (messageId: string, expanded: boolean) => void;
|
||||
expandedReasoningMessageIds: ReadonlySet<string>;
|
||||
workGroupViewState: WorkGroupViewState;
|
||||
agentPanelModel: AgentPanelModel;
|
||||
expandedSpawnEntryIds: ReadonlySet<string>;
|
||||
@@ -298,6 +301,7 @@ interface TimelineRowActivityState {
|
||||
isCompacting: boolean;
|
||||
isRevertingCheckpoint: boolean;
|
||||
latestTurnId: TurnId | null;
|
||||
unsettledTurnId: TurnId | null;
|
||||
/**
|
||||
* A worktree setup whose script is still running after the agent took
|
||||
* over. The working header shows it as a chip with a popover; the stage
|
||||
@@ -516,6 +520,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
const [expandedSpawnEntryIds, setExpandedSpawnEntryIds] = useState<ReadonlySet<string>>(
|
||||
new Set(),
|
||||
);
|
||||
const [expandedReasoningMessageIds, setExpandedReasoningMessageIds] = useState<
|
||||
ReadonlySet<string>
|
||||
>(new Set());
|
||||
const listIdentityKey = displayThreadKey ?? routeThreadKey;
|
||||
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)");
|
||||
const listIdentityRef = useRef(listIdentityKey);
|
||||
@@ -526,6 +533,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
let paintedExpandedTurnIds = expandedTurnIds;
|
||||
let paintedExpandedWorkGroupIds = expandedWorkGroupIds;
|
||||
let paintedExpandedSpawnEntryIds = expandedSpawnEntryIds;
|
||||
let paintedExpandedReasoningMessageIds = expandedReasoningMessageIds;
|
||||
if (listIdentityRef.current !== listIdentityKey) {
|
||||
listIdentityRef.current = listIdentityKey;
|
||||
previousLatestTurnRef.current = latestTurn;
|
||||
@@ -533,9 +541,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
paintedExpandedTurnIds = new Set();
|
||||
paintedExpandedWorkGroupIds = new Set();
|
||||
paintedExpandedSpawnEntryIds = new Set();
|
||||
paintedExpandedReasoningMessageIds = new Set();
|
||||
setExpandedTurnIds(paintedExpandedTurnIds);
|
||||
setExpandedWorkGroupIds(paintedExpandedWorkGroupIds);
|
||||
setExpandedSpawnEntryIds(paintedExpandedSpawnEntryIds);
|
||||
setExpandedReasoningMessageIds(paintedExpandedReasoningMessageIds);
|
||||
}
|
||||
const onToggleSpawnRow = useCallback((entryId: string, expanded: boolean) => {
|
||||
setExpandedSpawnEntryIds((current) => {
|
||||
@@ -660,6 +670,21 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
},
|
||||
[expandedWorkGroupIds, suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
const onToggleReasoning = useCallback(
|
||||
(messageId: string, expanded: boolean) => {
|
||||
// The anchor must be the timeline row id, which for a message row is the
|
||||
// message id, or position restoration is skipped for every row.
|
||||
suspendEndScrollMaintenanceForDisclosure(messageId, !expanded);
|
||||
setExpandedReasoningMessageIds((current) => {
|
||||
if (current.has(messageId) === expanded) return current;
|
||||
const next = new Set(current);
|
||||
if (expanded) next.add(messageId);
|
||||
else next.delete(messageId);
|
||||
return next;
|
||||
});
|
||||
},
|
||||
[suspendEndScrollMaintenanceForDisclosure],
|
||||
);
|
||||
|
||||
// An in-session interrupt leaves its turn expanded so the user keeps their
|
||||
// place; the next turn (or a reload, since this is local state) folds it.
|
||||
@@ -944,6 +969,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onToggleWorkGroup,
|
||||
onToggleWorkEntry: suspendEndScrollMaintenanceForDisclosure,
|
||||
onToggleSpawnRow,
|
||||
onToggleReasoning,
|
||||
expandedReasoningMessageIds: paintedExpandedReasoningMessageIds,
|
||||
workGroupViewState,
|
||||
agentPanelModel: agentPanelModel ?? EMPTY_AGENT_PANEL_MODEL,
|
||||
expandedSpawnEntryIds: paintedExpandedSpawnEntryIds,
|
||||
@@ -977,6 +1004,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
onToggleWorkGroup,
|
||||
suspendEndScrollMaintenanceForDisclosure,
|
||||
onToggleSpawnRow,
|
||||
onToggleReasoning,
|
||||
paintedExpandedReasoningMessageIds,
|
||||
workGroupViewState,
|
||||
agentPanelModel,
|
||||
paintedExpandedSpawnEntryIds,
|
||||
@@ -1003,6 +1032,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isCompacting,
|
||||
isRevertingCheckpoint,
|
||||
latestTurnId: latestTurn?.turnId ?? null,
|
||||
// The same value the row-derivation uses, so a block and the placeholder
|
||||
// beside it can never disagree about whether a turn is still live.
|
||||
unsettledTurnId: deriveUnsettledTurnId(latestTurn ?? null, runningTurnId),
|
||||
backgroundWorktreeSetup,
|
||||
}),
|
||||
[
|
||||
@@ -1011,7 +1043,12 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
isRevertingCheckpoint,
|
||||
isWorking,
|
||||
isPreparingWorktree,
|
||||
// Deliberately the fields `deriveUnsettledTurnId` reads, not the object:
|
||||
// its identity changes on every thread-shell patch.
|
||||
latestTurn?.turnId,
|
||||
latestTurn?.state,
|
||||
latestTurn?.completedAt,
|
||||
runningTurnId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1453,6 +1490,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
: (row.kind === "message" &&
|
||||
row.message.role === "assistant" &&
|
||||
!row.showAssistantMeta) ||
|
||||
(row.kind === "message" && row.message.role === "reasoning") ||
|
||||
row.kind === "work" ||
|
||||
row.kind === "work-live" ||
|
||||
row.kind === "work-toggle" ||
|
||||
@@ -1488,6 +1526,9 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
|
||||
{row.kind === "message" && row.message.role === "assistant" ? (
|
||||
<AssistantTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "message" && row.message.role === "reasoning" ? (
|
||||
<ReasoningTimelineRow row={row} />
|
||||
) : null}
|
||||
{row.kind === "assistant-meta" ? <AssistantMetaTimelineRow row={row} /> : null}
|
||||
{row.kind === "proposed-plan" ? <ProposedPlanTimelineRow row={row} /> : null}
|
||||
{row.kind === "working" ? <WorkingTimelineRow row={row} /> : null}
|
||||
@@ -2363,6 +2404,86 @@ function ThinkingTimelineRow() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A provider's thinking trace. Collapsed by default: reasoning is context for
|
||||
* the answer, not the answer. The open/closed flag lives on the list so it
|
||||
* survives row recycling in the virtualizer.
|
||||
*/
|
||||
const ReasoningTimelineRow = memo(function ReasoningTimelineRow({
|
||||
row,
|
||||
}: {
|
||||
row: Extract<TimelineRow, { kind: "message" }>;
|
||||
}) {
|
||||
const ctx = use(TimelineRowCtx);
|
||||
const { isWorking, unsettledTurnId } = use(TimelineRowActivityCtx);
|
||||
const { message } = row;
|
||||
// A block left open by a crashed provider or a restarted server never gets
|
||||
// its completion. Only the live turn may claim to still be thinking, so a
|
||||
// settled turn cannot shimmer "Thinking" at the user forever.
|
||||
const streaming =
|
||||
Boolean(message.streaming) &&
|
||||
isWorking &&
|
||||
message.turnId !== null &&
|
||||
message.turnId === unsettledTurnId;
|
||||
const expanded = ctx.expandedReasoningMessageIds.has(message.id);
|
||||
const { onToggleReasoning } = ctx;
|
||||
const toggle = useCallback(() => {
|
||||
onToggleReasoning(message.id, !expanded);
|
||||
}, [expanded, message.id, onToggleReasoning]);
|
||||
const label = streaming ? "Thinking" : "Thought";
|
||||
|
||||
if (message.text.trim().length === 0 && !streaming) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col", expanded && "mb-1")}>
|
||||
<button
|
||||
type="button"
|
||||
aria-expanded={expanded}
|
||||
onClick={toggle}
|
||||
className="flex cursor-pointer select-none items-center gap-1.5 rounded-md px-0.5 py-0.5 text-start transition-colors hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
|
||||
>
|
||||
<span className="flex size-6 shrink-0 items-center justify-center text-icon-muted">
|
||||
<BrainIcon aria-hidden className="block size-4 shrink-0 stroke-[1.8] opacity-70" />
|
||||
</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-1.5">
|
||||
<span
|
||||
ref={streaming ? observeVisibleAnimation : undefined}
|
||||
className="relative min-w-0 flex-1 truncate text-secondary-label text-sm leading-relaxed"
|
||||
>
|
||||
{label}
|
||||
{streaming ? <ActivityShimmerOverlay>{label}</ActivityShimmerOverlay> : null}
|
||||
</span>
|
||||
<span className="flex size-4 shrink-0 items-center justify-center" aria-hidden>
|
||||
<ChevronRightIcon
|
||||
className={cn(
|
||||
"size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
|
||||
expanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
{expanded ? (
|
||||
<div className="mt-1 ms-7 max-h-96 overflow-auto rounded-md bg-muted/40 px-3 py-2 text-secondary-label select-text">
|
||||
<ChatMarkdown
|
||||
text={message.text}
|
||||
cwd={ctx.markdownCwd}
|
||||
threadRef={ctx.threadRef ?? undefined}
|
||||
isStreaming={streaming}
|
||||
lineBreaks
|
||||
skills={ctx.skills}
|
||||
headingLevelOffset={MESSAGE_HEADING_LEVEL}
|
||||
onUseArtifactTemplate={ctx.onUseArtifactTemplate}
|
||||
onImageExpand={ctx.onImageExpand}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
function CompactingLabel() {
|
||||
return (
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
|
||||
@@ -187,7 +187,8 @@ const RESPONSE_STREAMING_MODE_LABELS: Record<ResponseStreamingMode, string> = {
|
||||
const RESPONSE_STREAMING_MODE_DESCRIPTIONS: Record<ResponseStreamingMode, string> = {
|
||||
turn: "Text appears once the agent finishes its turn.",
|
||||
paragraph: "Each paragraph or code block appears as soon as it is complete.",
|
||||
token: "Every token repaints the message as it arrives. Slower and harder to read.",
|
||||
token:
|
||||
"Every token repaints the answer as it arrives. Slower and harder to read. Thinking traces still arrive a paragraph at a time.",
|
||||
};
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
|
||||
@@ -65,8 +65,10 @@ const StoredShellSnapshotJson = Schema.fromJsonString(StoredShellSnapshot);
|
||||
// exists for rollback safety: a pre-pagination client would decode a windowed
|
||||
// v2 record, silently drop the unknown `page` field, and treat the partial
|
||||
// thread as complete forever. Older entries fail to decode → cold cache.
|
||||
// v4 reloads pre-thinking caches: their fallback system roles cannot recover
|
||||
// settled reasoning messages by resuming afterSequence.
|
||||
const StoredThreadSnapshot = Schema.Struct({
|
||||
schemaVersion: Schema.Literal(3),
|
||||
schemaVersion: Schema.Literal(4),
|
||||
environmentId: EnvironmentId,
|
||||
threadId: ThreadId,
|
||||
snapshot: OrchestrationThreadDetailSnapshot,
|
||||
@@ -679,7 +681,7 @@ export const connectionStorageLayer = Layer.effectContext(
|
||||
saveThread: (environmentId, snapshot) =>
|
||||
Effect.gen(function* () {
|
||||
const encoded = yield* encodeStoredThreadSnapshot({
|
||||
schemaVersion: 3,
|
||||
schemaVersion: 4,
|
||||
environmentId,
|
||||
threadId: snapshot.thread.id,
|
||||
snapshot,
|
||||
|
||||
@@ -1613,11 +1613,13 @@ export function createMessageAttachmentPreviewProjector() {
|
||||
};
|
||||
}
|
||||
|
||||
/** Text and update time do not change a streaming assistant message's timeline structure. */
|
||||
const streamsText = (role: ChatMessage["role"]) => role === "assistant" || role === "reasoning";
|
||||
|
||||
/** Text and update time do not change a streaming message's timeline structure. */
|
||||
export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
|
||||
if (
|
||||
previous.role !== "assistant" ||
|
||||
next.role !== "assistant" ||
|
||||
!streamsText(previous.role) ||
|
||||
previous.role !== next.role ||
|
||||
!previous.streaming ||
|
||||
!next.streaming
|
||||
) {
|
||||
|
||||
@@ -210,6 +210,7 @@ const LOADERS: ReadonlyArray<{
|
||||
...input,
|
||||
threadId: THREAD.thread.id,
|
||||
window: { turnLimit: 20, beforeCursor: "older-page" },
|
||||
reasoningMessages: true,
|
||||
}),
|
||||
},
|
||||
];
|
||||
@@ -252,6 +253,7 @@ describe("authenticated environment HTTP requests", () => {
|
||||
if (loader.name === "older thread history") {
|
||||
expect(url.searchParams.get("turnLimit")).toBe("20");
|
||||
expect(url.searchParams.get("beforeCursor")).toBe("older-page");
|
||||
expect(url.searchParams.get("reasoningMessages")).toBe("true");
|
||||
}
|
||||
expect(PREPARED.httpAuthorization).toMatchObject({ accessToken: "expired-token" });
|
||||
}),
|
||||
|
||||
@@ -42,6 +42,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
|
||||
readonly remoteAuthorization?: Option.Option<RemoteEnvironmentAuthorization["Service"]>;
|
||||
readonly timeoutMs?: number;
|
||||
readonly window?: ThreadSnapshotWindow;
|
||||
readonly reasoningMessages?: boolean;
|
||||
}) {
|
||||
return yield* executeAuthenticatedEnvironmentHttpRequest({
|
||||
...input,
|
||||
@@ -54,6 +55,7 @@ export const fetchEnvironmentThreadSnapshot = Effect.fn(
|
||||
client.threadSnapshot({
|
||||
params: { threadId: input.threadId },
|
||||
payload: {
|
||||
...(input.reasoningMessages === true ? { reasoningMessages: "true" as const } : {}),
|
||||
...(input.window !== undefined ? { turnLimit: input.window.turnLimit } : {}),
|
||||
...(input.window?.beforeCursor !== undefined
|
||||
? { beforeCursor: input.window.beforeCursor }
|
||||
@@ -79,6 +81,7 @@ export class ThreadSnapshotLoader extends Context.Service<
|
||||
prepared: PreparedConnection,
|
||||
threadId: ThreadId,
|
||||
window?: ThreadSnapshotWindow,
|
||||
reasoningMessages?: boolean,
|
||||
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>>;
|
||||
}
|
||||
>()("@t3tools/client-runtime/state/threadSnapshotHttp/ThreadSnapshotLoader") {}
|
||||
@@ -97,12 +100,18 @@ export const threadSnapshotLoaderLayer: Layer.Layer<
|
||||
const signer = yield* Effect.serviceOption(ManagedRelayDpopSigner);
|
||||
const remoteAuthorization = yield* Effect.serviceOption(RemoteEnvironmentAuthorization);
|
||||
return ThreadSnapshotLoader.of({
|
||||
load: (prepared: PreparedConnection, threadId: ThreadId, window?: ThreadSnapshotWindow) =>
|
||||
load: (
|
||||
prepared: PreparedConnection,
|
||||
threadId: ThreadId,
|
||||
window?: ThreadSnapshotWindow,
|
||||
reasoningMessages?: boolean,
|
||||
) =>
|
||||
fetchEnvironmentThreadSnapshot({
|
||||
prepared,
|
||||
threadId,
|
||||
signer,
|
||||
remoteAuthorization,
|
||||
...(reasoningMessages === true ? { reasoningMessages: true } : {}),
|
||||
...(window !== undefined ? { window } : {}),
|
||||
}).pipe(
|
||||
Effect.map(Option.some<OrchestrationThreadDetailSnapshot>),
|
||||
|
||||
@@ -133,6 +133,7 @@ type LoaderResponse = Option.Option<OrchestrationThreadDetailSnapshot>;
|
||||
|
||||
const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (options?: {
|
||||
readonly paginationCapability?: boolean;
|
||||
readonly reasoningCapability?: boolean;
|
||||
readonly initialResponse?: LoaderResponse;
|
||||
/** Cached snapshot returned by the cache store (simulates a warm cache). */
|
||||
readonly cached?: OrchestrationThreadDetailSnapshot;
|
||||
@@ -140,6 +141,7 @@ const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (opt
|
||||
const inputs = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
|
||||
const observed = yield* Queue.unbounded<EnvironmentThreadState>();
|
||||
const loaderWindows = yield* Ref.make<ReadonlyArray<ThreadSnapshotWindow | undefined>>([]);
|
||||
const loaderReasoning = yield* Ref.make<ReadonlyArray<boolean | undefined>>([]);
|
||||
const lastSubscribeInput = yield* Ref.make<Record<string, unknown> | undefined>(undefined);
|
||||
const savedThreads = yield* Ref.make<ReadonlyArray<OrchestrationThreadDetailSnapshot>>([]);
|
||||
// Older-page responses resolve through deferreds so tests can interleave
|
||||
@@ -156,6 +158,7 @@ const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (opt
|
||||
client,
|
||||
initialConfig: Effect.succeed({
|
||||
threadSnapshotPagination: options?.paginationCapability !== false,
|
||||
reasoningMessages: options?.reasoningCapability === true,
|
||||
} as never),
|
||||
subscribeServerConfig: (input) => client.subscribeServerConfig(input),
|
||||
ready: Effect.void,
|
||||
@@ -169,8 +172,9 @@ const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (opt
|
||||
Option.some(PREPARED),
|
||||
);
|
||||
const snapshotLoader = ThreadSnapshotLoader.of({
|
||||
load: (_prepared, _threadId, window) =>
|
||||
load: (_prepared, _threadId, window, reasoningMessages) =>
|
||||
Ref.update(loaderWindows, (current) => [...current, window]).pipe(
|
||||
Effect.andThen(Ref.update(loaderReasoning, (current) => [...current, reasoningMessages])),
|
||||
Effect.andThen(
|
||||
window?.beforeCursor === undefined
|
||||
? Effect.succeed(
|
||||
@@ -231,6 +235,7 @@ const makeHarness = Effect.fn("TestThreadPagination.makeHarness")(function* (opt
|
||||
awaitState,
|
||||
resolveNextPage,
|
||||
loaderWindows,
|
||||
loaderReasoning,
|
||||
lastSubscribeInput,
|
||||
savedThreads,
|
||||
threadState,
|
||||
@@ -287,6 +292,32 @@ const revertEvent = (sequence: number): OrchestrationThreadStreamItem => ({
|
||||
});
|
||||
|
||||
describe("thread pagination state", () => {
|
||||
for (const reasoningCapability of [false, true]) {
|
||||
it.effect(
|
||||
`negotiates reasoning for initial, older and socket reads: ${reasoningCapability}`,
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({
|
||||
reasoningCapability,
|
||||
initialResponse: Option.some(WINDOWED_SNAPSHOT),
|
||||
});
|
||||
yield* harness.awaitState((value) => Option.isSome(value.page));
|
||||
const input = yield* Ref.get(harness.lastSubscribeInput);
|
||||
expect(input?.reasoningMessages).toBe(reasoningCapability ? true : undefined);
|
||||
expect(yield* Ref.get(harness.loaderReasoning)).toEqual([reasoningCapability]);
|
||||
expect(requestOlderThreadTurns(TARGET.environmentId, THREAD_ID)).toBe(true);
|
||||
yield* harness.resolveNextPage(Option.some(OLDER_PAGE));
|
||||
yield* harness.awaitState((value) =>
|
||||
Option.match(value.page, { onNone: () => false, onSome: (page) => !page.hasMore }),
|
||||
);
|
||||
expect(yield* Ref.get(harness.loaderReasoning)).toEqual([
|
||||
reasoningCapability,
|
||||
reasoningCapability,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.effect("windows the initial load when the server advertises pagination", () =>
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeHarness({ initialResponse: Option.some(WINDOWED_SNAPSHOT) });
|
||||
|
||||
@@ -258,6 +258,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
// from the session config. Gates loadOlderTurns so a reconnect to a
|
||||
// pre-pagination server never sends unsupported window parameters.
|
||||
const paginationSupported = yield* Ref.make(false);
|
||||
const reasoningMessagesSupported = yield* Ref.make(false);
|
||||
// An older page whose thread watermark is ahead of the live state, parked
|
||||
// until the subscription catches up (see mergeOlderPage's caller). At most
|
||||
// one can exist because loadOlderTurns no-ops while loadingOlder is true.
|
||||
@@ -336,6 +337,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
// window parameters to a server that may not accept them (review
|
||||
// finding). makeSubscribeInput re-sets it from the next session's config.
|
||||
yield* Ref.set(paginationSupported, false);
|
||||
yield* Ref.set(reasoningMessagesSupported, false);
|
||||
yield* SubscriptionRef.update(state, (current) => ({
|
||||
...current,
|
||||
status: current.status === "deleted" ? current.status : statusWithoutLiveData(current.data),
|
||||
@@ -655,7 +657,12 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
turnLimit: OLDER_THREAD_PAGE_USER_TURN_LIMIT,
|
||||
beforeCursor: page.beforeCursor,
|
||||
};
|
||||
const response = yield* snapshotLoader.load(prepared, threadId, window);
|
||||
const response = yield* snapshotLoader.load(
|
||||
prepared,
|
||||
threadId,
|
||||
window,
|
||||
yield* Ref.get(reasoningMessagesSupported),
|
||||
);
|
||||
// Staleness check and merge run under the same lock as stream-item
|
||||
// application, so a revert/snapshot cannot land between them (TOCTOU
|
||||
// review finding) — anything that rewrites history bumps the epoch
|
||||
@@ -747,6 +754,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
({}) as {
|
||||
threadResumeCompletionMarker?: boolean;
|
||||
threadSnapshotPagination?: boolean;
|
||||
reasoningMessages?: boolean;
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -755,6 +763,8 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
// servers reject unknown query params, and a windowed WS fallback to
|
||||
// such a server would silently hide history.
|
||||
const supportsPagination = config.threadSnapshotPagination === true;
|
||||
const supportsReasoningMessages = config.reasoningMessages === true;
|
||||
yield* Ref.set(reasoningMessagesSupported, supportsReasoningMessages);
|
||||
yield* Ref.set(paginationSupported, supportsPagination);
|
||||
yield* Ref.set(awaitingCompletion, supportsCompletionMarker);
|
||||
yield* markSynchronizing;
|
||||
@@ -801,6 +811,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
prepared,
|
||||
threadId,
|
||||
supportsPagination ? { turnLimit: INITIAL_THREAD_USER_TURN_LIMIT } : undefined,
|
||||
supportsReasoningMessages,
|
||||
);
|
||||
if (Option.isSome(httpSnapshot)) {
|
||||
yield* applyItem({ kind: "snapshot", snapshot: httpSnapshot.value });
|
||||
@@ -822,6 +833,7 @@ export const makeEnvironmentThreadState = Effect.fn("EnvironmentThreadState.make
|
||||
threadId,
|
||||
...(canResume ? { afterSequence: sequence } : {}),
|
||||
...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),
|
||||
...(supportsReasoningMessages ? { reasoningMessages: true as const } : {}),
|
||||
// The WS fallback snapshot (sent when afterSequence is missing or
|
||||
// the gap is too large) should be windowed the same as the HTTP
|
||||
// path; without this a resume failure re-downloads the full thread.
|
||||
|
||||
@@ -498,6 +498,7 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({
|
||||
// to strings). Both fields optional: omitting them keeps the full-snapshot
|
||||
// behavior, so pagination stays opt-in per request.
|
||||
const EnvironmentOrchestrationThreadSnapshotQuery = {
|
||||
reasoningMessages: Schema.optional(Schema.Literal("true")),
|
||||
turnLimit: Schema.optional(
|
||||
Schema.FiniteFromString.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(1)),
|
||||
),
|
||||
|
||||
@@ -539,7 +539,15 @@ export const OrchestrationProject = Schema.Struct({
|
||||
});
|
||||
export type OrchestrationProject = typeof OrchestrationProject.Type;
|
||||
|
||||
export const OrchestrationMessageRole = Schema.Literals(["user", "assistant", "system"]);
|
||||
/** `reasoning` carries a provider's thinking trace: a reasoning summary, or
|
||||
* the raw chain of thought when the model exposes one. It is a sibling of the
|
||||
* assistant text it precedes, not a replacement for it. */
|
||||
export const OrchestrationMessageRole = Schema.Literals([
|
||||
"user",
|
||||
"assistant",
|
||||
"system",
|
||||
"reasoning",
|
||||
]);
|
||||
export type OrchestrationMessageRole = typeof OrchestrationMessageRole.Type;
|
||||
|
||||
export const OrchestrationMessage = Schema.Struct({
|
||||
@@ -973,6 +981,8 @@ export type OrchestrationSubscribeShellInput = typeof OrchestrationSubscribeShel
|
||||
|
||||
export const OrchestrationSubscribeThreadInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
/** Opt in to reasoning roles; older clients receive system messages instead. */
|
||||
reasoningMessages: Schema.optionalKey(Schema.Boolean),
|
||||
/**
|
||||
* When provided, the server skips the initial snapshot frame and instead
|
||||
* replays events after this sequence before streaming live events. Clients
|
||||
@@ -1471,6 +1481,25 @@ const ThreadMessageAssistantCompleteCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadMessageReasoningDeltaCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.message.reasoning.delta"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
delta: Schema.String,
|
||||
turnId: Schema.optional(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadMessageReasoningCompleteCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.message.reasoning.complete"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
turnId: Schema.optional(TurnId),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadHistoryImportCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.history.import"),
|
||||
commandId: CommandId,
|
||||
@@ -1599,6 +1628,8 @@ const InternalOrchestrationCommand = Schema.Union([
|
||||
ThreadSessionSetCommand,
|
||||
ThreadMessageAssistantDeltaCommand,
|
||||
ThreadMessageAssistantCompleteCommand,
|
||||
ThreadMessageReasoningDeltaCommand,
|
||||
ThreadMessageReasoningCompleteCommand,
|
||||
ThreadHistoryImportCommand,
|
||||
ThreadMessageUserAppendCommand,
|
||||
ThreadProposedPlanUpsertCommand,
|
||||
|
||||
@@ -579,6 +579,8 @@ export const ServerConfig = Schema.Struct({
|
||||
* fields to servers that don't advertise this.
|
||||
*/
|
||||
threadSnapshotPagination: Schema.optionalKey(Schema.Boolean),
|
||||
/** Whether thread reads accept the reasoningMessages opt-in. */
|
||||
reasoningMessages: Schema.optionalKey(Schema.Boolean),
|
||||
/**
|
||||
* Palettes published by this environment's machine. Never sent in a config
|
||||
* snapshot: the theme stream emits the current set before any change, so a
|
||||
|
||||
Reference in new issue
Block a user