Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 7e514b697c Merge telemetry test clock layer
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:09:50 +00:00
Cursor AgentandJulius Marminge bed379a80b Assert platform realPath failure details
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:08:12 +00:00
Cursor AgentandJulius Marminge 2ba8472afb Use idiomatic Effect filesystem and duration APIs
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 16:06:42 +00:00
9 changed files with 215 additions and 332 deletions

No files matched your search

@@ -2,8 +2,10 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -72,6 +74,7 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provideMerge(NodeHttpServer.layerTest),
Layer.provideMerge(TestClock.layer()),
);
yield* Effect.gen(function* () {
@@ -117,4 +120,64 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
);
}),
);
it.effect("periodic flush runs on the TestClock-controlled interval", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
const receivedRequest = yield* Deferred.make<void>();
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
prefix: "t3-telemetry-interval-",
});
const telemetryLayer = AnalyticsService.layer.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
T3CODE_TELEMETRY_ENABLED: true,
T3CODE_POSTHOG_KEY: "phc_test_key",
T3CODE_POSTHOG_HOST: "",
T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
}),
);
const batchServerLayer = HttpServer.serve(
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
if (request.method !== "POST") {
return HttpServerResponse.empty({ status: 404 });
}
const payload = yield* request.json.pipe(
Effect.map((body) => body as RecordedBatchRequest["body"]),
Effect.orElseSucceed(() => null),
);
capturedRequests.push({ path: request.url, body: payload });
yield* Deferred.succeed(receivedRequest, undefined);
return HttpServerResponse.jsonUnsafe({});
}),
);
const runtimeLayer = telemetryLayer.pipe(
Layer.provide(configLayer),
Layer.provideMerge(NodeHttpServer.layerTest),
);
yield* Effect.gen(function* () {
yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped);
const analytics = yield* AnalyticsService.AnalyticsService;
yield* analytics.record("test.flush.interval", { index: 1 });
assert.equal(capturedRequests.length, 0);
yield* TestClock.adjust(AnalyticsService.ANALYTICS_FLUSH_INTERVAL);
yield* Deferred.await(receivedRequest).pipe(Effect.timeout("1 second"), TestClock.withLive);
}).pipe(Effect.provide(runtimeLayer));
const batchRequests = capturedRequests.filter(
(request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
Array.isArray(request.body?.batch),
);
assert.equal(batchRequests.length, 1);
assert.equal(batchRequests[0]?.body.batch[0]?.event, "test.flush.interval");
}),
);
});
@@ -10,6 +10,7 @@ import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/ho
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -28,6 +29,8 @@ interface BufferedAnalyticsEvent {
readonly capturedAt: string;
}
export const ANALYTICS_FLUSH_INTERVAL = Duration.seconds(1);
const TelemetryEnvConfig = Config.all({
posthogKey: Config.string("T3CODE_POSTHOG_KEY").pipe(
Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
@@ -172,7 +175,7 @@ export const make = Effect.gen(function* () {
},
);
yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
yield* Effect.forever(Effect.sleep(ANALYTICS_FLUSH_INTERVAL).pipe(Effect.flatMap(() => flush)), {
disableYield: true,
}).pipe(Effect.forkScoped);
@@ -1,9 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { assert, it, describe, expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as ServerConfig from "../config.ts";
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
@@ -185,8 +186,9 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
assert.instanceOf(error.cause, PlatformError.PlatformError);
assert.equal((error.cause as PlatformError.PlatformError).reason._tag, "NotFound");
assert.equal((error.cause as PlatformError.PlatformError).reason.method, "realPath");
}),
);
});
@@ -140,30 +140,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const realWorkspaceRoot = yield* fileSystem.realPath(input.cwd).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
),
);
const realTargetPath = yield* fileSystem.realPath(target.absolutePath).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
),
);
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
+1
View File
@@ -4729,6 +4729,7 @@ function ChatViewContent(props: ChatViewProps) {
<MessagesTimeline
key={activeThread.id}
isWorking={isWorking}
activeTurnInProgress={isWorking || !latestTurnSettled}
activeTurnStartedAt={activeWorkStartedAt}
listRef={legendListRef}
timelineEntries={timelineEntries}
@@ -879,69 +879,6 @@ describe("deriveMessagesTimelineRows", () => {
expect(assistantRow?.showAssistantMeta).toBe(false);
expect(assistantRow?.showAssistantCopyButton).toBe(false);
});
it("marks only the unsettled turn work row as in progress", () => {
const rows = deriveMessagesTimelineRows({
timelineEntries: [
{
id: "old-work-entry",
kind: "work",
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "old-work",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Read files",
tone: "tool" as const,
},
},
{
id: "user-entry",
kind: "message",
createdAt: "2026-01-01T00:00:12Z",
message: {
id: "user-message" as never,
role: "user",
text: "Continue",
turnId: null,
createdAt: "2026-01-01T00:00:12Z",
updatedAt: "2026-01-01T00:00:12Z",
streaming: false,
},
},
{
id: "active-work-entry",
kind: "work",
createdAt: "2026-01-01T00:00:18Z",
entry: {
id: "active-work",
createdAt: "2026-01-01T00:00:18Z",
turnId: "turn-2" as never,
label: "Run tests",
tone: "tool" as const,
},
},
],
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:16Z",
completedAt: null,
},
expandedTurnIds: new Set(["turn-1" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const workRows = rows.filter((row) => row.kind === "work");
expect(workRows.map((row) => [row.id, row.turnInProgress])).toEqual([
["old-work-entry", false],
["active-work-entry", true],
]);
});
});
describe("computeStableMessagesTimelineRows", () => {
@@ -1050,92 +987,6 @@ describe("computeStableMessagesTimelineRows", () => {
expect(repeated.result[0]).toBe(initial.result[0]);
});
it("reuses settled work rows when a different turn stops running", () => {
const timelineEntries = [
{
id: "old-work-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:08Z",
entry: {
id: "old-work",
createdAt: "2026-01-01T00:00:08Z",
turnId: "turn-1" as never,
label: "Read files",
tone: "tool" as const,
},
},
{
id: "user-entry",
kind: "message" as const,
createdAt: "2026-01-01T00:00:12Z",
message: {
id: "user-message" as never,
role: "user" as const,
text: "Continue",
turnId: null,
createdAt: "2026-01-01T00:00:12Z",
updatedAt: "2026-01-01T00:00:12Z",
streaming: false,
},
},
{
id: "active-work-entry",
kind: "work" as const,
createdAt: "2026-01-01T00:00:18Z",
entry: {
id: "active-work",
createdAt: "2026-01-01T00:00:18Z",
turnId: "turn-2" as never,
label: "Run tests",
tone: "tool" as const,
},
},
];
const runningRows = deriveMessagesTimelineRows({
timelineEntries,
latestTurn: {
turnId: "turn-2" as never,
state: "running",
startedAt: "2026-01-01T00:00:16Z",
completedAt: null,
},
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const initial = computeStableMessagesTimelineRows(runningRows, {
byId: new Map(),
result: [],
});
const settledRows = deriveMessagesTimelineRows({
timelineEntries,
latestTurn: {
turnId: "turn-2" as never,
state: "completed",
startedAt: "2026-01-01T00:00:16Z",
completedAt: "2026-01-01T00:00:30Z",
},
expandedTurnIds: new Set(["turn-1" as never, "turn-2" as never]),
isWorking: false,
activeTurnStartedAt: null,
turnDiffSummaryByAssistantMessageId: new Map(),
revertTurnCountByUserMessageId: new Map(),
});
const repeated = computeStableMessagesTimelineRows(settledRows, initial);
expect(repeated.result.find((row) => row.id === "old-work-entry")).toBe(
initial.result.find((row) => row.id === "old-work-entry"),
);
expect(repeated.result.find((row) => row.id === "active-work-entry")).not.toBe(
initial.result.find((row) => row.id === "active-work-entry"),
);
});
it("returns a new result when row order changes without content changes", () => {
const firstUserMessage = {
id: "user-1" as never,
@@ -41,7 +41,6 @@ export type MessagesTimelineRow =
id: string;
createdAt: string;
groupedEntries: WorkLogEntry[];
turnInProgress: boolean;
}
| {
kind: "turn-fold";
@@ -362,9 +361,6 @@ export function deriveMessagesTimelineRows(input: {
id: timelineEntry.id,
createdAt: timelineEntry.createdAt,
groupedEntries,
turnInProgress:
unsettledTurnId !== null &&
groupedEntries.some((entry) => entry.turnId === unsettledTurnId),
});
index = cursor - 1;
continue;
@@ -464,10 +460,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
return a.proposedPlan === (b as typeof a).proposedPlan;
case "work":
return (
a.turnInProgress === (b as typeof a).turnInProgress &&
Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries)
);
return Equal.equals(a.groupedEntries, (b as typeof a).groupedEntries);
case "message": {
const bm = b as typeof a;
@@ -93,6 +93,7 @@ const MESSAGE_CREATED_AT = "2026-03-17T19:12:28.000Z";
function buildProps() {
return {
isWorking: false,
activeTurnInProgress: false,
activeTurnStartedAt: null,
listRef: createRef<LegendListRef | null>(),
latestTurn: null,
+114 -147
View File
@@ -17,10 +17,8 @@ import {
useMemo,
useRef,
useState,
type Dispatch,
type KeyboardEvent,
type ReactNode,
type SetStateAction,
} from "react";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
@@ -131,12 +129,14 @@ interface TimelineRowSharedState {
onToggleTurnFold: (turnId: TurnId) => void;
}
interface TimelineRevertControlsState {
disabled: boolean;
interface TimelineRowActivityState {
isWorking: boolean;
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
const TimelineRevertControlsCtx = createContext<TimelineRevertControlsState>(null!);
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
@@ -147,6 +147,7 @@ const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "d
interface MessagesTimelineProps {
isWorking: boolean;
activeTurnInProgress: boolean;
activeTurnStartedAt: string | null;
listRef: React.RefObject<LegendListRef | null>;
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
@@ -173,6 +174,7 @@ interface MessagesTimelineProps {
export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
activeTurnInProgress,
activeTurnStartedAt,
listRef,
timelineEntries,
@@ -213,11 +215,52 @@ export const MessagesTimeline = memo(function MessagesTimeline({
return next;
});
}, []);
useFoldToggleSettlingReset(foldToggleSettling, setFoldToggleSettling);
useEffect(() => {
if (!foldToggleSettling) {
return;
}
let secondFrameId: number | null = null;
const firstFrameId = window.requestAnimationFrame(() => {
secondFrameId = window.requestAnimationFrame(() => {
setFoldToggleSettling(false);
});
});
return () => {
window.cancelAnimationFrame(firstFrameId);
if (secondFrameId !== null) {
window.cancelAnimationFrame(secondFrameId);
}
};
}, [foldToggleSettling]);
// 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.
useLatestTurnFoldState(latestTurn, setExpandedTurnIds);
const previousLatestTurnRef = useRef(latestTurn);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = latestTurn;
if (!latestTurn || previous?.turnId === undefined) {
return;
}
if (latestTurn.turnId === previous.turnId) {
if (previous.state === "running" && latestTurn.state === "interrupted") {
setExpandedTurnIds((existing) => {
const next = new Set(existing);
next.add(latestTurn.turnId);
return next;
});
}
return;
}
setExpandedTurnIds((existing) => {
if (!existing.has(previous.turnId)) {
return existing;
}
const next = new Set(existing);
next.delete(previous.turnId);
return next;
});
}, [latestTurn]);
const rawRows = useMemo(
() =>
@@ -249,7 +292,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
}
}, [listRef, onIsAtEndChange]);
useInitialTimelineEndScroll(rows.length, listRef, onIsAtEndChange);
const previousRowCountRef = useRef(rows.length);
useEffect(() => {
const previousRowCount = previousRowCountRef.current;
previousRowCountRef.current = rows.length;
if (previousRowCount > 0 || rows.length === 0) {
return;
}
onIsAtEndChange(true);
const frameId = window.requestAnimationFrame(() => {
void listRef.current?.scrollToEnd?.({ animated: false });
});
return () => {
window.cancelAnimationFrame(frameId);
};
}, [listRef, onIsAtEndChange, rows.length]);
const sharedState = useMemo<TimelineRowSharedState>(
() => ({
@@ -280,11 +339,13 @@ export const MessagesTimeline = memo(function MessagesTimeline({
onToggleTurnFold,
],
);
const revertControlsState = useMemo<TimelineRevertControlsState>(
const activityState = useMemo<TimelineRowActivityState>(
() => ({
disabled: isRevertingCheckpoint || isWorking,
isWorking,
isRevertingCheckpoint,
activeTurnInProgress,
}),
[isRevertingCheckpoint, isWorking],
[activeTurnInProgress, isRevertingCheckpoint, isWorking],
);
// Stable renderItem — no closure deps. Row components read shared state
@@ -310,7 +371,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
return (
<TimelineRowCtx value={sharedState}>
<TimelineRevertControlsCtx value={revertControlsState}>
<TimelineRowActivityCtx value={activityState}>
<LegendList<MessagesTimelineRow>
ref={listRef}
data={rows}
@@ -326,92 +387,11 @@ export const MessagesTimeline = memo(function MessagesTimeline({
ListHeaderComponent={TIMELINE_LIST_HEADER}
ListFooterComponent={TIMELINE_LIST_FOOTER}
/>
</TimelineRevertControlsCtx>
</TimelineRowActivityCtx>
</TimelineRowCtx>
);
});
function useFoldToggleSettlingReset(
foldToggleSettling: boolean,
setFoldToggleSettling: Dispatch<SetStateAction<boolean>>,
) {
useEffect(() => {
if (!foldToggleSettling) {
return;
}
let secondFrameId: number | null = null;
const firstFrameId = window.requestAnimationFrame(() => {
secondFrameId = window.requestAnimationFrame(() => {
setFoldToggleSettling(false);
});
});
return () => {
window.cancelAnimationFrame(firstFrameId);
if (secondFrameId !== null) {
window.cancelAnimationFrame(secondFrameId);
}
};
}, [foldToggleSettling, setFoldToggleSettling]);
}
function useLatestTurnFoldState(
latestTurn: TimelineLatestTurn | null,
setExpandedTurnIds: Dispatch<SetStateAction<ReadonlySet<TurnId>>>,
) {
const previousLatestTurnRef = useRef(latestTurn);
useEffect(() => {
const previous = previousLatestTurnRef.current;
previousLatestTurnRef.current = latestTurn;
if (!latestTurn || previous?.turnId === undefined) {
return;
}
if (latestTurn.turnId === previous.turnId) {
if (previous.state === "running" && latestTurn.state === "interrupted") {
setExpandedTurnIds((existing) => {
const next = new Set(existing);
next.add(latestTurn.turnId);
return next;
});
}
return;
}
setExpandedTurnIds((existing) => {
if (!existing.has(previous.turnId)) {
return existing;
}
const next = new Set(existing);
next.delete(previous.turnId);
return next;
});
}, [latestTurn, setExpandedTurnIds]);
}
function useInitialTimelineEndScroll(
rowCount: number,
listRef: React.RefObject<LegendListRef | null>,
onIsAtEndChange: (isAtEnd: boolean) => void,
) {
const previousRowCountRef = useRef(rowCount);
useEffect(() => {
const previousRowCount = previousRowCountRef.current;
previousRowCountRef.current = rowCount;
if (previousRowCount > 0 || rowCount === 0) {
return;
}
onIsAtEndChange(true);
const frameId = window.requestAnimationFrame(() => {
void listRef.current?.scrollToEnd?.({ animated: false });
});
return () => {
window.cancelAnimationFrame(frameId);
};
}, [listRef, onIsAtEndChange, rowCount]);
}
function keyExtractor(item: MessagesTimelineRow) {
return item.id;
}
@@ -442,7 +422,7 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
data-message-id={row.kind === "message" ? row.message.id : undefined}
data-message-role={row.kind === "message" ? row.message.role : undefined}
>
{row.kind === "work" ? <WorkGroupSection row={row} /> : null}
{row.kind === "work" ? <WorkGroupSection groupedEntries={row.groupedEntries} /> : null}
{row.kind === "turn-fold" ? <TurnFoldTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "user" ? <UserTimelineRow row={row} /> : null}
{row.kind === "message" && row.message.role === "assistant" ? (
@@ -560,7 +540,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
const ctx = use(TimelineRowCtx);
const controls = use(TimelineRevertControlsCtx);
const activity = use(TimelineRowActivityCtx);
return (
<Tooltip>
@@ -570,7 +550,7 @@ function RevertUserMessageButton({ messageId }: { messageId: MessageId }) {
type="button"
size="xs"
variant="ghost"
disabled={controls.disabled}
disabled={activity.isRevertingCheckpoint || activity.isWorking}
onClick={() => ctx.onRevertUserMessage(messageId)}
aria-label="Revert to this message"
/>
@@ -711,16 +691,7 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
function WorkingTimer({ createdAt }: { createdAt: string }) {
const textRef = useRef<HTMLSpanElement>(null);
const initialText = formatWorkingTimerNow(createdAt);
useWorkingTimerText(textRef, createdAt);
return (
<span ref={textRef} className="tabular-nums">
{initialText}
</span>
);
}
function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, createdAt: string) {
useEffect(() => {
const updateText = () => {
if (textRef.current) {
@@ -730,7 +701,13 @@ function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, c
updateText();
const id = setInterval(updateText, 1000);
return () => clearInterval(id);
}, [createdAt, textRef]);
}, [createdAt]);
return (
<span ref={textRef} className="tabular-nums">
{initialText}
</span>
);
}
// ---------------------------------------------------------------------------
@@ -740,15 +717,14 @@ function useWorkingTimerText(textRef: React.RefObject<HTMLSpanElement | null>, c
/** Collapsed state shows the earliest chunk so "Show more" only appends rows downward. */
const WorkGroupSection = memo(function WorkGroupSection({
row,
groupedEntries,
}: {
row: Extract<MessagesTimelineRow, { kind: "work" }>;
groupedEntries: Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"];
}) {
const { workspaceRoot } = use(TimelineRowCtx);
const [isExpanded, setIsExpanded] = useState(false);
const sectionRef = useRef<HTMLElement>(null);
const anchorBottomBeforeToggleRef = useRef<number | null>(null);
const { groupedEntries, turnInProgress } = row;
const nonEmptyEntries = useMemo(
() => groupedEntries.filter((entry) => !workEntryIndicatesToolNeutralStatus(entry)),
[groupedEntries],
@@ -766,7 +742,31 @@ const WorkGroupSection = memo(function WorkGroupSection({
: `${nonEmptyEntries.length} tool calls`
: "Work Log";
usePreserveWorkGroupAnchorOnExpand(isExpanded, sectionRef, anchorBottomBeforeToggleRef);
useLayoutEffect(() => {
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
anchorBottomBeforeToggleRef.current = null;
if (anchorBottomBeforeToggle === null) {
return;
}
const section = sectionRef.current;
if (!section) {
return;
}
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
if (Math.abs(delta) < 0.5) {
return;
}
const scroller = findNearestVerticalScroller(section);
if (scroller) {
scroller.scrollTop += delta;
} else {
window.scrollBy(0, delta);
}
}, [isExpanded]);
const toggleExpanded = () => {
anchorBottomBeforeToggleRef.current =
@@ -788,7 +788,6 @@ const WorkGroupSection = memo(function WorkGroupSection({
<SimpleWorkEntryRow
key={workEntry.id}
workEntry={workEntry}
turnInProgress={turnInProgress}
workspaceRoot={workspaceRoot}
/>
))}
@@ -819,38 +818,6 @@ const WorkGroupSection = memo(function WorkGroupSection({
);
});
function usePreserveWorkGroupAnchorOnExpand(
isExpanded: boolean,
sectionRef: React.RefObject<HTMLElement | null>,
anchorBottomBeforeToggleRef: React.RefObject<number | null>,
) {
useLayoutEffect(() => {
const anchorBottomBeforeToggle = anchorBottomBeforeToggleRef.current;
anchorBottomBeforeToggleRef.current = null;
if (anchorBottomBeforeToggle === null) {
return;
}
const section = sectionRef.current;
if (!section) {
return;
}
const delta = section.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
if (Math.abs(delta) < 0.5) {
return;
}
const scroller = findNearestVerticalScroller(section);
if (scroller) {
scroller.scrollTop += delta;
} else {
window.scrollBy(0, delta);
}
}, [anchorBottomBeforeToggleRef, isExpanded, sectionRef]);
}
function findNearestVerticalScroller(element: HTMLElement): HTMLElement | null {
let parent = element.parentElement;
while (parent) {
@@ -1578,10 +1545,10 @@ const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation(
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
turnInProgress: boolean;
workspaceRoot: string | undefined;
}) {
const { workEntry, turnInProgress, workspaceRoot } = props;
const { workEntry, workspaceRoot } = props;
const activity = use(TimelineRowActivityCtx);
const [expanded, setExpanded] = useState(false);
const iconConfig = workToneIcon(workEntry.tone);
const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
@@ -1616,7 +1583,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
: showDestructiveRowStyle
? "font-medium text-destructive"
: "font-medium text-foreground/82";
const turnSettled = !turnInProgress;
const turnSettled = !activity.activeTurnInProgress;
const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry);
const showSuccessIndicator =
workEntryIndicatesToolSuccess(workEntry) ||