Skip to content

Commit bf29021

Browse files
Merge remote-tracking branch 'origin/main' into pr-32585
2 parents 46c3834 + d313b2a commit bf29021

6 files changed

Lines changed: 306 additions & 17 deletions

File tree

‎apps/server/src/orchestration-v2/testkit/fixtures/message_steering/cursor_transcript.ndjson‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
{"type":"emit_inbound","label":"thinking-delta","frame":{"type":"interaction.update","runId":"run-046488f0-f621-4d59-976c-c4c935ad1282","update":{"type":"thinking-delta","text":"The user requested the"}}}
77
{"type":"expect_outbound","label":"run.cancel:1","frame":{"type":"run.cancel","runId":"run-046488f0-f621-4d59-976c-c4c935ad1282"}}
88
{"type":"emit_inbound","label":"run.completed:1","frame":{"type":"run.completed","result":{"id":"run-046488f0-f621-4d59-976c-c4c935ad1282","requestId":"d3b97820-1cf3-448d-a4b1-5fa7edc21460","status":"cancelled","model":{"id":"composer-2.5"},"durationMs":3177}}}
9-
{"type":"expect_outbound","label":"run.start:2","frame":{"type":"run.start","message":"Actually, respond with exactly: steering fixture observed","options":{"model":{"id":"composer-2.5"},"mode":"agent"}}}
9+
{"type":"expect_outbound","label":"run.start:2","frame":{"type":"run.start","message":"Your previous turn was interrupted and is missing from your history. Some of its work may already be done. Its request was:\n\nRespond with exactly: steering fixture initial response\n\nThe new message, which may continue or change that request:\n\nActually, respond with exactly: steering fixture observed","options":{"model":{"id":"composer-2.5"},"mode":"agent"}}}
1010
{"type":"emit_inbound","label":"run.started:2","frame":{"type":"run.started","runId":"run-e3b66d77-b2d4-4791-be2b-1a35c8e997d1","agentId":"agent-575fd75e-3fd7-412e-9b74-36f3a5aa5371"}}
1111
{"type":"emit_inbound","label":"thinking-delta","frame":{"type":"interaction.update","runId":"run-e3b66d77-b2d4-4791-be2b-1a35c8e997d1","update":{"type":"thinking-delta","text":"The response will be"}}}
1212
{"type":"emit_inbound","label":"token-delta","frame":{"type":"interaction.update","runId":"run-e3b66d77-b2d4-4791-be2b-1a35c8e997d1","update":{"type":"token-delta","tokens":5}}}

‎apps/web/src/components/chat/MessagesTimeline.browser.test.tsx‎

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,110 @@ describe("MessagesTimeline messages", () => {
469469
await expectHeadingInView("Last turn", "Turn 118:");
470470
});
471471

472+
it("disables the minimap's next turn button at the bottom of the thread", async () => {
473+
setup();
474+
const props = baseProps();
475+
const entries = Array.from({ length: 16 }, (_, index) => [
476+
message(`Question ${index}`, {}, `user-${index}`),
477+
message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`),
478+
]).flat();
479+
await using screen = await renderTimeline(entries, props);
480+
const viewport = props.listRef.current!.getScrollableNode()!;
481+
const strips = () => [
482+
...screen.container.querySelectorAll<HTMLElement>("[data-minimap-strip]"),
483+
];
484+
// Several final turns share the last screen, so the current turn is not the last one.
485+
await vi.waitFor(() => {
486+
expect(viewport.scrollTop).toBeGreaterThan(0);
487+
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2);
488+
expect(strips()[0]?.dataset.inView).toBe("false");
489+
expect(
490+
strips()
491+
.slice(-2)
492+
.map((strip) => strip.dataset.inView),
493+
).toEqual(["true", "true"]);
494+
expect(screen.button("Previous turn")).not.toBeDisabled();
495+
});
496+
497+
expect(screen.button("Next turn")).toBeDisabled();
498+
499+
viewport.scrollTop -= 30;
500+
await vi.waitFor(() => expect(screen.button("Next turn")).not.toBeDisabled());
501+
502+
// Shrinking a detached viewport moves the bottom away without a scroll event.
503+
await screen.rerender(
504+
<MessagesTimeline {...props} timelineEntries={entries} liveFollowEnabled={false} />,
505+
);
506+
viewport.scrollTop = viewport.scrollHeight;
507+
await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled());
508+
screen.container.style.height = "600px";
509+
await vi.waitFor(() => {
510+
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan(
511+
500,
512+
);
513+
expect(screen.button("Next turn")).not.toBeDisabled();
514+
});
515+
516+
// So does a footer that grows below a detached bottom.
517+
viewport.scrollTop = viewport.scrollHeight;
518+
await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled());
519+
await screen.rerender(
520+
<MessagesTimeline
521+
{...props}
522+
timelineEntries={entries}
523+
liveFollowEnabled={false}
524+
footer={<div style={{ height: 400 }} />}
525+
/>,
526+
);
527+
await vi.waitFor(() => {
528+
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan(
529+
300,
530+
);
531+
expect(screen.button("Next turn")).not.toBeDisabled();
532+
});
533+
});
534+
535+
it("enables the minimap's next turn button on a thread restored above its bottom", async () => {
536+
setup();
537+
const base = baseProps();
538+
const turns = (prefix: string) =>
539+
Array.from({ length: 16 }, (_, index) => [
540+
message(`${prefix} question ${index}`, {}, `${prefix}-user-${index}`),
541+
message(`${prefix} answer ${index}`, { role: "assistant" }, `${prefix}-assistant-${index}`),
542+
]).flat();
543+
const other = "environment-local:thread-minimap-restored";
544+
rememberTimelinePosition(
545+
other,
546+
{ rowId: "entry-b-user-4", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
547+
false,
548+
);
549+
await using screen = await renderElement(
550+
<MessagesTimeline {...base} timelineEntries={turns("a")} />,
551+
);
552+
const viewport = base.listRef.current!.getScrollableNode()!;
553+
await vi.waitFor(() => {
554+
expect(viewport.scrollTop).toBeGreaterThan(0);
555+
expect(screen.button("Next turn")).toBeDisabled();
556+
});
557+
558+
await screen.rerender(
559+
<MessagesTimeline
560+
{...base}
561+
routeThreadKey={other}
562+
timelineEntries={turns("b")}
563+
liveFollowEnabled={false}
564+
/>,
565+
);
566+
await vi.waitFor(() => {
567+
const row = screen.container.querySelector('[data-timeline-row-id="entry-b-user-4"]');
568+
expect(row).not.toBeNull();
569+
expect(
570+
Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top),
571+
).toBeLessThanOrEqual(2);
572+
expect(screen.button("Next turn")).not.toBeDisabled();
573+
});
574+
});
575+
472576
it("keeps rows in item order after a reload or thread switch, before any timer runs", async () => {
473577
setup();
474578
// NVDA's browse mode keeps the first DOM order it reads, so a timer that sorts rows later is too late.

‎apps/web/src/components/chat/MessagesTimeline.tsx‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -794,6 +794,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
794794
};
795795
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
796796
const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
797+
const [minimapAtEnd, setMinimapAtEnd] = useState(false);
797798
const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
798799
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
799800
onAnchorReady(anchorMessageId, info.anchorIndex);
@@ -864,17 +865,27 @@ const ConversationTimeline = memo(function ConversationTimeline({
864865
setMinimapCurrentIndex((current) =>
865866
current === nextCurrentIndex ? current : nextCurrentIndex,
866867
);
868+
// The exact bottom, not the follow re-arm zone: Next can still scroll inside that zone.
869+
setMinimapAtEnd(
870+
viewport !== undefined &&
871+
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= 1,
872+
);
867873
});
868874

869875
const minimapRefreshFrameRef = useRef<number | null>(null);
870-
const scheduleMinimapRefresh = () => {
876+
const scheduleMinimapRefresh = useStableCallback(() => {
871877
if (minimapRefreshFrameRef.current !== null) return;
872878
// LegendList recycles row containers before React commits their positions.
873879
minimapRefreshFrameRef.current = requestAnimationFrame(() => {
874880
minimapRefreshFrameRef.current = null;
875881
refreshMinimap();
876882
});
877-
};
883+
});
884+
885+
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the minimap skips refreshes until the restore commits, and the restore can land without a scroll event
886+
useLayoutEffect(() => {
887+
if (!restoringThreadPosition) scheduleMinimapRefresh();
888+
}, [restoringThreadPosition, scheduleMinimapRefresh]);
878889

879890
// The measurement the last remember wrote, so a follow release can rewrite
880891
// it without reading render state from a listener.
@@ -970,9 +981,10 @@ const ConversationTimeline = memo(function ConversationTimeline({
970981
const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {
971982
setTimelineViewportElement(viewportElement);
972983
if (!viewportElement) return;
973-
const stopObserving = observeResize(viewportElement, () =>
974-
measureTimelineGutter(viewportElement),
975-
);
984+
const stopObserving = observeResize(viewportElement, () => {
985+
measureTimelineGutter(viewportElement);
986+
scheduleMinimapRefresh();
987+
});
976988
return () => {
977989
stopObserving();
978990
setTimelineViewportElement(null);
@@ -1323,6 +1335,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
13231335
maintainScrollAtEndThreshold={1}
13241336
onScroll={handleScroll}
13251337
onItemSizeChanged={scheduleMinimapRefresh}
1338+
onMetricsChange={scheduleMinimapRefresh}
13261339
className={cn(
13271340
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
13281341
topFadeEnabled && "topbar-scroll-fade",
@@ -1335,6 +1348,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
13351348
hasPersistentGutter={minimapHasPersistentGutter}
13361349
hitStripWidth={minimapHitStripWidth}
13371350
currentIndex={minimapCurrentIndex}
1351+
atEnd={minimapAtEnd}
13381352
stripMap={minimapStripMap}
13391353
onWheel={forwardMinimapWheel}
13401354
onSelect={(item) => {

‎apps/web/src/components/chat/TimelineMinimap.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ export function TimelineMinimap({
3838
hasPersistentGutter,
3939
hitStripWidth,
4040
currentIndex,
41+
atEnd,
4142
items,
4243
stripMap,
4344
onWheel,
@@ -46,6 +47,7 @@ export function TimelineMinimap({
4647
hasPersistentGutter: boolean;
4748
hitStripWidth: number;
4849
currentIndex: number | null;
50+
atEnd: boolean;
4951
items: ReadonlyArray<TimelineMinimapItem>;
5052
stripMap: Map<string, HTMLSpanElement>;
5153
onWheel: (event: WheelEvent) => void;
@@ -84,7 +86,8 @@ export function TimelineMinimap({
8486
currentIndex !== null && currentIndex >= 0 && currentIndex < items.length ? currentIndex : null;
8587
const previousItem =
8688
resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
87-
const nextItem = resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex + 1] ?? null);
89+
const nextItem =
90+
resolvedCurrentIndex === null || atEnd ? null : (items[resolvedCurrentIndex + 1] ?? null);
8891

8992
const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
9093
const rect = event.currentTarget.getBoundingClientRect();

‎packages/provider-cursor/src/server/adapter.test.ts‎

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
ThreadId,
1515
} from "@t3tools/contracts";
1616
import * as DateTime from "effect/DateTime";
17+
import * as Deferred from "effect/Deferred";
1718
import * as Effect from "effect/Effect";
1819
import * as FileSystem from "effect/FileSystem";
1920
import * as Layer from "effect/Layer";
@@ -812,6 +813,151 @@ describe("CursorAdapterV2", () => {
812813
),
813814
);
814815

816+
it.effect("carries an interrupted prompt into the steer that restarts the turn", () =>
817+
Effect.gen(function* () {
818+
const fileSystem = yield* FileSystem.FileSystem;
819+
const workspace = yield* fileSystem.makeTempDirectoryScoped({ prefix: "cursor-v2-steer-" });
820+
const sentMessages: Array<string> = [];
821+
const runEnds: Array<Deferred.Deferred<"finished" | "cancelled">> = [];
822+
const instanceId = ProviderInstanceId.make("cursor");
823+
const threadId = ThreadId.make("cursor-steer-thread");
824+
const modelSelection = { instanceId, model: "composer-2.5" };
825+
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
826+
runtimeMode: "full-access",
827+
interactionMode: "default",
828+
cwd: workspace,
829+
});
830+
const adapter = yield* makeCursorAdapterV2({
831+
instanceId,
832+
environment: { HOME: workspace },
833+
}).pipe(
834+
Effect.provideService(CursorAgentSdk.CursorAgentSdkRunner, {
835+
assertComplete: Effect.void,
836+
open: () =>
837+
Effect.succeed({
838+
agentId: "native-cursor-steer",
839+
listMessages: Effect.succeed([]),
840+
close: Effect.void,
841+
send: (input) =>
842+
Effect.gen(function* () {
843+
sentMessages.push(
844+
typeof input.message === "string" ? input.message : input.message.text,
845+
);
846+
const runId = `native-cursor-run-${sentMessages.length}`;
847+
const ended = yield* Deferred.make<"finished" | "cancelled">();
848+
runEnds.push(ended);
849+
return {
850+
agentId: "native-cursor-steer",
851+
runId,
852+
// Cursor drops a cancelled run's prompt from the agent's conversation.
853+
wait: Deferred.await(ended).pipe(
854+
Effect.map((status) => ({
855+
id: runId,
856+
requestId: `native-request-${sentMessages.length}`,
857+
status,
858+
model: { id: "composer-2.5" },
859+
durationMs: 1,
860+
})),
861+
),
862+
cancel: Deferred.succeed(ended, "cancelled"),
863+
};
864+
}),
865+
}),
866+
}),
867+
Effect.provide(TestProviderHost.layer({ cwd: workspace })),
868+
);
869+
const runtime = yield* adapter.openSession({
870+
threadId,
871+
providerSessionId: ProviderSessionId.make("cursor-steer-session"),
872+
modelSelection,
873+
runtimePolicy,
874+
});
875+
const providerThread = yield* runtime.ensureThread({
876+
threadId,
877+
modelSelection,
878+
runtimePolicy,
879+
});
880+
const now = yield* DateTime.now;
881+
const appThread = {
882+
id: threadId,
883+
projectId: ProjectId.make("cursor-steer-project"),
884+
createdBy: "user" as const,
885+
creationSource: "web" as const,
886+
title: "Cursor steer",
887+
providerInstanceId: instanceId,
888+
modelSelection,
889+
runtimeMode: "full-access" as const,
890+
interactionMode: "default" as const,
891+
branch: null,
892+
worktreePath: null,
893+
activeProviderThreadId: providerThread.id,
894+
lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },
895+
forkedFrom: null,
896+
createdAt: now,
897+
updatedAt: now,
898+
archivedAt: null,
899+
settledOverride: null,
900+
settledAt: null,
901+
lastVisitedAt: null,
902+
deletedAt: null,
903+
};
904+
const turnInput = (runOrdinal: number, text: string) => ({
905+
threadId,
906+
providerThread,
907+
modelSelection,
908+
runtimePolicy,
909+
runId: RunId.make(`cursor-steer-run-${runOrdinal}`),
910+
runOrdinal,
911+
providerTurnOrdinal: runOrdinal,
912+
attemptId: RunAttemptId.make(`cursor-steer-attempt-${runOrdinal}`),
913+
rootNodeId: NodeId.make(`cursor-steer-root-${runOrdinal}`),
914+
appThread,
915+
message: {
916+
messageId: MessageId.make(`cursor-steer-message-${runOrdinal}`),
917+
createdBy: "user" as const,
918+
creationSource: "web" as const,
919+
text,
920+
attachments: [],
921+
},
922+
});
923+
const firstPrompt = "Write me a 1000 word story about a dog.";
924+
const steerText = "No wait, a pig please.";
925+
926+
yield* runtime.startTurn(turnInput(1, firstPrompt));
927+
const started = Option.getOrThrow(
928+
yield* runtime.events.pipe(
929+
Stream.filter((event) => event.type === "provider_turn.updated"),
930+
Stream.runHead,
931+
),
932+
);
933+
assert(started.type === "provider_turn.updated");
934+
yield* runtime.interruptTurn({ providerThread, providerTurnId: started.providerTurn.id });
935+
yield* runtime.startTurn(turnInput(2, steerText));
936+
937+
assert.lengthOf(sentMessages, 2);
938+
const steered = sentMessages[1]!;
939+
assert.include(steered, steerText);
940+
assert.include(
941+
steered,
942+
firstPrompt,
943+
"the interrupted prompt is missing from the run that replaces it",
944+
);
945+
946+
yield* Deferred.succeed(runEnds[1]!, "finished");
947+
yield* runtime.events.pipe(
948+
Stream.filter((event) => event.type === "turn.terminal" && event.status === "completed"),
949+
Stream.runHead,
950+
);
951+
yield* runtime.startTurn(turnInput(3, "Now a cow."));
952+
assert.notInclude(sentMessages[2]!, firstPrompt, "a finished turn carries nothing forward");
953+
}).pipe(
954+
Effect.scoped,
955+
Effect.provide(
956+
Layer.mergeAll(NodeServices.layer, IdAllocator.layer, McpProviderSessions.layer),
957+
),
958+
),
959+
);
960+
815961
it.effect("projects Cursor directory trees and lint diagnostics as file search results", () =>
816962
Effect.gen(function* () {
817963
const fileSystem = yield* FileSystem.FileSystem;

0 commit comments

Comments
 (0)